查找<;br/>;标记内部<;ins></ins>;标记并替换它


Find <br/> tag inside <ins> </ins> tags and replace it

例如,我有:

<br/>
<ins>
<br/>
<br/>
</ins>

我想找到<ins></ins>标签之间的所有<br/>,并将它们更改为:<br/>&lt;br/&gt;。这个修复程序将允许我的diff算法实际换行并显示插入了新行。现在的例子是:

<br/>
<ins>
<br/>&lt;br/&gt;
<br/>&lt;br/&gt;
</ins>

我不知道如何用PHP来做这件事。我知道它需要使用preg_replacepreg_replace_callback,但我不知道如何使用regex表达式。

使用PHP,(使用逻辑)

<?php
$content = "<br/>
<ins>
<br/>
<br/>
</ins>
<ins>
<br/>
<br/>
</ins>
<br/>";
// Find all the positions from where <ins> is starting
$lastPos = 0;
$positions = array();
$count = 1;
while(($lastPos = strpos($content,"<ins>",$lastPos))!==false) {
    $positions[] = $lastPos;$lastPos=$lastPos+strlen("<ins>");
}
foreach($positions as $value) {
    ${"one".$count} = $value;$count++;
}
// Find all the positions from where </ins> is starting
$lastPos = 0;
$positions = array();
$count = 1;
while(($lastPos = strpos($content,"</ins>",$lastPos))!==false) {
    $positions[] = $lastPos;$lastPos=$lastPos+strlen("</ins>");
}
foreach($positions as $value) {
    ${"two".$count} = $value;$count++;
}
// Store the elements present inside all the <ins></ins> tags in PHP variables and replace <br/> with <br/>&lt;br/&gt;
for($i=1;$i<=$count-1;$i++)
{
    ${"area".$i} = substr($content,${"one".$i}+5,${"two".$i}-${"one".$i}-5);
    if(strpos(${"area".$i},"<br/>")) ${"area_new".$i} = str_replace("<br/>","<br/>&lt;br/&gt;",${"area".$i});
}
for($i=1;$i<=$count-1;$i++)
{
    $content = str_replace(${"area".$i},${"area_new".$i},$content);
}
// Now $content contains what you wanted it to be.
?>

或者,(使用预定义功能)

<?php
$content = "<br/>
<ins>
<br/>
<br/>
</ins>
<ins>
<br/>
<br/>
</ins>
<br/>";
$content = preg_replace('~(?:<ins>|(?!^)'G)'s*<br'/>~', '$0&lt;br/&gt;', $content);
?>