PHP:从HTML字符串中删除特定标记?

时间:2010-07-22 11:56:53

标签: php

我有以下html:

<html>
 <body>
 bla bla bla bla
  <div id="myDiv"> 
         more text
      <div id="anotherDiv">
           And even more text
      </div>
  </div>

  bla bla bla
 </body>
</html>

我想删除从<div id="anotherDiv">开始直至结束<div>的所有内容。我该怎么做?

9 个答案:

答案 0 :(得分:32)

native DOM

$dom = new DOMDocument;
$dom->loadHTML($htmlString);
$xPath = new DOMXPath($dom);
$nodes = $xPath->query('//*[@id="anotherDiv"]');
if($nodes->item(0)) {
    $nodes->item(0)->parentNode->removeChild($nodes->item(0));
}
echo $dom->saveHTML();

答案 1 :(得分:16)

您可以使用preg_replace()之类的:

$string = preg_replace('/<div id="someid"[^>]+\>/i', "", $string);

答案 2 :(得分:7)

除了Haim Evgi使用preg_replace()的回答:

<强>功能

function strip_single_tag($str,$tag){

    $str=preg_replace('/<'.$tag.'[^>]*>/i', '', $str);

    $str=preg_replace('/<\/'.$tag.'>/i', '', $str);

    return $str;
}   

修改

处理strip_single_tag('<pre>abc</pre>','p');

function strip_single_tag($str,$tag){

    $str1=preg_replace('/<\/'.$tag.'>/i', '', $str);

    if($str1 != $str){

        $str=preg_replace('/<'.$tag.'[^>]*>/i', '', $str1);
    }

    return $str;
}

<强>资源

https://gist.github.com/rafasashi/59c9448f5467ea427fa3

答案 3 :(得分:4)

您也可以使用Simple HTML DOM

  

用PHP5 +编写的HTML DOM解析器让您可以非常轻松地操作HTML   方式!

答案 4 :(得分:2)

strip_tags()函数就是你要找的。

http://us.php.net/manual/en/function.strip-tags.php

答案 5 :(得分:1)

drpcken

说得好

假设你有

$ title =&#34;管理帖子&#34;;

然后你就可以用它了 strip_tags($ title,&#39; title&#39;);

它只会让你回复管理帖子

答案 6 :(得分:1)

我写这些来剥离特定的标签和属性。由于他们是正则表达式,他们并非100%保证在所有情况下都可以工作,但这对我来说是一个公平的权衡:

// Strips only the given tags in the given HTML string.
function strip_tags_blacklist($html, $tags) {
    foreach ($tags as $tag) {
        $regex = '#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi';
        $html = preg_replace($regex, '', $html);
    }
    return $html;
}

// Strips the given attributes found in the given HTML string.
function strip_attributes($html, $atts) {
    foreach ($atts as $att) {
        $regex = '#\b' . $att . '\b(\s*=\s*[\'"][^\'"]*[\'"])?(?=[^<]*>)#msi';
        $html = preg_replace($regex, '', $html);
    }
    return $html;
}

答案 7 :(得分:0)

怎么样?

// Strips only the given tags in the given HTML string.
function strip_tags_blacklist($html, $tags) {
    $html = preg_replace('/<'. $tags .'\b[^>]*>(.*?)<\/'. $tags .'>/is', "", $html);
    return $html;
}

答案 8 :(得分:0)

在RafaSashi使用 browser = request.META['HTTP_USER_AGENT'] data = {"browser": browser} database.child("browser").child('localId').child("details").set(data) return render(request, "home.html", {"e": email}) 回答之后,以下是适用于单个标签或标签数组的版本:

preg_replace()