在<ins> </ins>标签内找到标签并替换它

时间:2015-12-03 21:09:40

标签: php regex

例如我有:

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

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

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

我不知道如何用PHP做到这一点。我知道它需要使用preg_replacepreg_replace_callback,但我不知道正则表达式是我自己做的。

1 个答案:

答案 0 :(得分:0)

使用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);
?>