dongyuan3094 2017-05-02 14:03
浏览 5
已采纳

当特定子字符串存在时,删除两个 之间的部分[PHP]

I have a variable in which I store some HTML code. Let's say:

<div> 
<span> test of {my_string} </span> 
{my_string} 
test of {my_string} 
</div> 
<h1> {my_string} </h1>

I would need to remove some lines containing a specific value so the end result looks like:

<div>
</div>

So I was thinking of getting the position of the string with strpos and then get the which are before and after. But how can I search backwards with strpos as I already have an offset specified?

$rep_pos = strpos($message, 'my_string');
$line_begining = ????
$line_end = strpos($message, '
', $rep_pos);

I can't use strip_tags because I don't know in advance what will be the tags around and some other strings can use the same tags.

  • 写回答

1条回答 默认 最新

  • doushou8730 2017-05-02 14:13
    关注

    You should use DOMDocument for parsing HTML tags string. Here we are using XPath query which is //*[text()=" my_string "] which means get all elements which contains my_string text.

    Try this code snippet here

    <?php
    
    ini_set('display_errors', 1);
    
    $string='<html>
               <body>
                 <div>
                   <span> my_string </span>
                 </div>
                 <h1> my_string </h1>
               </body>
             </html>';
    $domobject= new DOMDocument();
    $domobject->loadHTML($string);
    $xpath= new DOMXPath($domobject);
    $result=$xpath->query('//*[text()=" my_string "]');
    Foreach($result as $nodes)
    {
        $nodes->parentNode->removeChild($nodes);
    }
    echo $domobject->saveHTML();
    

    Solution 2:

    Regex demo

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

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址