3v4l.org

run code in 300+ PHP versions simultaneously
<?php $content = <<<_HTML <!doctype html><html><head><title>What</title></head><body><p>(what)</p><div id="main"><p><span>what?</span></p><ul><li><span>foo</span> what!</li><li>(what?)</li></ul></div><p>(what)</p></body></html> _HTML; $find = ['(', ')', '?', '!']; $replace = ['(&#8202;', '&#8202;)', '&#8202;?', '&#8202;!']; $selector = implode(' or ', array_map(function($char) { return sprintf('contains(text(), "%s")', $char); }, $find)); $query = sprintf('//div[@id="main"]//*[%s]/text()', $selector); $doc = new DOMDocument(); $doc->loadHTML($content); $xpath = new DOMXPath($doc); $elements = $xpath->query($query); foreach ($elements as $element) { $element->nodeValue = html_entity_decode(str_replace($find, $replace, $element->nodeValue)); } echo $doc->saveHTML();
Output for 7.2.0 - 7.2.34, 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
<!DOCTYPE html> <html><head><title>What</title></head><body><p>(what)</p><div id="main"><p><span>what&#8202;?</span></p><ul><li><span>foo</span> what&#8202;!</li><li>(&#8202;what&#8202;?&#8202;)</li></ul></div><p>(what)</p></body></html>

preferences:
164.24 ms | 408 KiB | 5 Q