fork download
  1. <?php
  2.  
  3. $html = <<<EOF
  4. <p>Hi Hello <a href="#">World</a></p>.
  5. This is <div class="myclass">testing <a href="#">content</a>. some more content</div>.
  6. One more <a href="#"> Link </a>.
  7. EOF;
  8.  
  9. $dom = new DOMDocument();
  10. $dom->loadHTML($html);
  11.  
  12. $xpath = new DOMXpath($dom);
  13.  
  14. $links = $xpath->query("//a[not(ancestor::div[@class='myclass'])]");
  15.  
  16. foreach ($links as $link) {
  17. $link->parentNode->removeChild($link);
  18. }
  19.  
  20. // just to test it out
  21. echo $dom->saveHTML();
  22. ?>
Success #stdin #stdout 0.03s 52480KB
stdin
Standard input is empty
stdout
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://w...content-available-to-author-only...3.org/TR/REC-html40/loose.dtd">
<html><body><p>Hi Hello </p>.
This is <div class="myclass">testing <a href="#">content</a>. some more content</div>.
One more .</body></html>