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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?