3v4l.org

run code in 300+ PHP versions simultaneously
<?php $document = "<html> <a href='do not keep'><div>DO NOT KEEP1</div></a> <a href='do keep' data-link='keepLink'>Keep Link</a> <a href='do not keep'>DO NOT KEEP2</a> </html>"; $dom = new DOMDocument; $dom->loadXml($document); // load the file $xpath = new DOMXPath($dom); $nodes = $xpath->query('//a[not(@data-link=\'keepLink\')]'); // search for links that do not have the 'data-link' attribute set to 'keepLink' foreach($nodes as $element){ $textInside = $element->nodeValue; // get the text inside the link $parentNode = $element->parentNode; // save parent node $parentNode->replaceChild(new DOMText($textInside), $element); // remove the element } $myNewHTML = $dom->saveHTML(); // see http://php.net/manual/ro/domdocument.savehtml.php for limitations such as auto-adding of doc-type echo $myNewHTML;
Output for 5.6.0 - 5.6.38, 7.0.0 - 7.0.33, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
<html> DO NOT KEEP1 <a href="do%20keep" data-link="keepLink">Keep Link</a> DO NOT KEEP2 </html>

preferences:
159.35 ms | 408 KiB | 5 Q