简体   繁体   English

PHP str_replace循环中

[英]PHP str_replace in loop

i have two strings 我有两个弦

  $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';

I need to find <emph aid:cstyle="ITALIC"> protocol</emph> This kind of tag and find the same text in $tex and replace the word "protocol" with {it protocol } . 我需要找到<emph aid:cstyle="ITALIC"> protocol</emph>这种标签,并在$tex找到相同的文本,并用{it protocol }替换单词"protocol"

Simply 只是

i need to find this pattern 我需要找到这种模式

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

and find the text inside that pattern and replace the same word in $tex. 并找到该模式内的文本,并替换$ tex中的相同单词。

FYI : Content-wise both are same $tex and $xml . 仅供参考:内容方面都是相同的$tex$xml

I used this code 我用了这段代码

  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;

But it replace only one. 但它只替换一个。

You should change your regex to 您应该将正则表达式更改为

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

I tried it on your sample string and it finds both. 我在您的示例字符串上尝试过它,并且找到了两者。

Your current regex consumes to much of the string. 您当前的正则表达式消耗了大部分字符串。 If you run it on the provided string you will see that it matches more than you intended it to match 如果在提供的字符串上运行它,您将看到它比预期的要匹配的更多

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

Since the next "<" is already matched the matcher can not find the next opening tag. 由于下一个“ <”已匹配,匹配器找不到下一个开始标签。

For the loop-part: You are not overwriting $tex but you are using it as the string to work on. 对于循环部分:您不会覆盖$ tex,而是将其用作要处理的字符串。 So any changes but the last will not be stored. 因此,除了最后一次的任何更改都不会被存储。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM