例如我有:
<br/>
<ins>
<br/>
<br/>
</ins>
我想在<br/>
和<ins>
代码之间找到所有</ins>
,并将其更改为:<br/><br/>
。这个修复程序将允许我的diff算法实际进行换行并显示插入了新行。现在示例如下:
<br/>
<ins>
<br/><br/>
<br/><br/>
</ins>
我不知道如何用PHP做到这一点。我知道它需要使用preg_replace
或preg_replace_callback
,但我不知道正则表达式是我自己做的。
答案 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/><br/>
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/><br/>",${"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<br/>', $content);
?>