dongyuan3094 2017-05-02 06: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 06: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

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

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部