如何使用标签的 id 去除标签及其所有内部 html?

2021-12-25 00:00:00 replace tags php html domparser

我有以下 html:

<身体>bla bla bla bla<div id="myDiv">更多文字<div id="anotherDiv">还有更多文字

布拉布拉布拉

我想删除从

开始直到结束

的所有内容.我该怎么做?

解决方案

With nativeDOM

$dom = 新的 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();

I have the following 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>

I want to remove everything starting from <div id="anotherDiv"> until its closing <div>. How do I do that?

解决方案

With 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();

相关文章