duancao1951 2015-12-03 21:09
浏览 43
已采纳

在<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 21: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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟