duancao1951 2015-12-03 13:09
浏览 44
已采纳

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

For example I have:

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

I want to find all <br/> between <ins> and </ins> tags and change them to: <br/>&lt;br/&gt;. This fix would allow my diff algorithm to actually make a line break and show that new line was inserted. Example now would look:

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

I have no idea how to do this with PHP. I know it would require to use preg_replace or preg_replace_callback, but I have no knowledge of regex expressions to do it on my own.

  • 写回答

1条回答 默认 最新

  • dsa122870 2015-12-03 13:41
    关注

    Using PHP, (using logic)

    <?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.
    ?>
    

    or, (using predefined function)

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

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部