3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = <<<HTML Meet God's General Kathryn Kuhlman. <br> <img class="lazy_responsive" title="Kathryn Kuhlman - iUseFaith.com" src="https://www.iusefaith.com/ojm_thumbnail/1000/32f808f79011a7c0bd1ffefc1365c856.jpg" alt="Kathryn Kuhlman - iUseFaith.com" width="1600" height="517" /> <br> Follow <a href="https://www.iusefaith.com/en-354" title="Kathryn Kuhlman">Kathryn Kuhlman</a> <br> Max KANTCHEDE & Kathryn Kuhlman HTML; $keywords = [ 'Kathryn Kuhlman' => 'https://www.example.com/en-354', 'Max KANTCHEDE' => 'https://www.example.com/MaxKANTCHEDE', 'eneral' => 'https://www.example.com/this-is-not-used', ]; libxml_use_internal_errors(true); $dom = new DOMDocument(); $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $xpath = new DOMXPath($dom); $lookup = []; $regexNeedles = []; foreach ($keywords as $name => $link) { $lookup[strtolower($name)] = $link; $regexNeedles[] = preg_quote($name, '~'); } $pattern = '~\b(' . implode('|', $regexNeedles) . ')\b~i' ; foreach($xpath->query('//*[not(self::img or self::a)]/text()') as $textNode) { $newNodes = []; $hasReplacement = false; foreach (preg_split($pattern, $textNode->nodeValue, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $fragment) { $fragmentLower = strtolower($fragment); if (isset($lookup[$fragmentLower])) { $hasReplacement = true; $a = $dom->createElement('a'); $a->setAttribute('href', $lookup[$fragmentLower]); $a->setAttribute('title', $fragment); $a->nodeValue = $fragment; $newNodes[] = $a; } else { $newNodes[] = $dom->createTextNode($fragment); } } if ($hasReplacement) { $newFragment = $dom->createDocumentFragment(); foreach ($newNodes as $newNode) { $newFragment->appendChild($newNode); } $textNode->parentNode->replaceChild($newFragment, $textNode); } } echo substr(trim($dom->saveHTML()), 3, -4);
Output for 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
Meet God's General <a href="https://www.example.com/en-354" title="Kathryn Kuhlman">Kathryn Kuhlman</a>. <br> <img class="lazy_responsive" title="Kathryn Kuhlman - iUseFaith.com" src="https://www.iusefaith.com/ojm_thumbnail/1000/32f808f79011a7c0bd1ffefc1365c856.jpg" alt="Kathryn Kuhlman - iUseFaith.com" width="1600" height="517"> <br> Follow <a href="https://www.iusefaith.com/en-354" title="Kathryn Kuhlman">Kathryn Kuhlman</a> <br> <a href="https://www.example.com/MaxKANTCHEDE" title="Max KANTCHEDE">Max KANTCHEDE</a> &amp; <a href="https://www.example.com/en-354" title="Kathryn Kuhlman">Kathryn Kuhlman</a>

preferences:
101.4 ms | 409 KiB | 5 Q