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

2022-01-18 00:00:00 replace tags php html domparser

我有以下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> 的所有内容.我该怎么做?

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

推荐答案

With nativeDOM

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

相关文章