【问题标题】:PHP str_replace in loopPHP str_replace 在循环中
【发布时间】:2023-04-02 20:10:01
【问题描述】:

我有两个字符串

  $xml = '<para aid:pstyle="NL_FIRST">—To the best of our knowledge, the MMSN<emph aid:cstyle="ITALIC"> protocol</emph> is the first multifrequency<emph aid:cstyle="ITALIC"> MAC protocol especially</emph> designed for WSNs, in which each device is equipped with a single radio transceiver and the MAC layer packet size is very small.</para></item><item>';
  $tex = '\begin{itemize}\item o the best of our knowledge, the MMSN protocol is the first multifrequency MAC protocol especially designed for WSNs, in which each device is equipped with a single radio transceiver and the MAC layer packet size is very small.\item';

我需要找到&lt;emph aid:cstyle="ITALIC"&gt; protocol&lt;/emph&gt;这种标签,并在$tex中找到相同的文字并将"protocol"这个词替换为{it protocol }

简单

我需要找到这个模式

<emph aid:cstyle="ITALIC"> protocol</emph>

并找到该模式中的文本并替换 $tex 中的相同单词。

仅供参考:在内容方面两者都是相同的 $tex$xml

我用过这段代码

  preg_match_all('/<emph aid:cstyle="ITALIC">(.*?)<\/emph>(.*?)\</',$xml,$matches);

  for($i=0;$i<count($matches[1]);$i++)
   {

    $findtext = str_replace("<","",$matches[1][$i].$matches[2][$i]);    

$replace  = "{\it".$matches[1][$i]."}".$matches[2][$i];

$finaltext = preg_replace('/'.$findtext.'/',$replace,$tex);

    }

     echo $finaltext;

但它只替换一个。

【问题讨论】:

  • 您的问题是什么?请帮我找到一个不符合条件的解决方案。

标签: php xml string for-loop


【解决方案1】:

您应该将您的正则表达式更改为

preg_match_all('/<emph aid:cstyle="ITALIC">(.+?)<\/emph>/', $xml, $matches);

我在您的示例字符串上进行了尝试,并且两者都找到了。

您当前的正则表达式消耗了大部分字符串。如果你在提供的字符串上运行它,你会发现它匹配的比你想要的要多

string(71) "<emph aid:cstyle="ITALIC"> protocol</emph> is the first multifrequency<"

由于下一个“

对于循环部分:您没有覆盖 $tex,而是将其用作要处理的字符串。因此,除了最后一个之外的任何更改都不会被存储。

$finaltext = $tex;
for ($i = 0; $i <count($matches[1]); $i++) {
    $finaltext = str_replace($matches[1][$i], '{\it'.$matches[1][$i].'}', $finaltext);
}
echo $finaltext;

【讨论】:

  • 我更改了正则表达式。但它仍然只替换一个值。知道为什么它只匹配一个值。
  • 在每次迭代中,您都在处理永远不会更改的 $tex-string。您将更改保存到 $finaltext。检查更新的版本,它应该可以工作。另外,我冒昧地将循环中的正则表达式替换为更简单、更快的 str_replace。
  • @Dipen Baskaran:这个解决方案有帮助吗?
猜你喜欢
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多