generate functionMon, 07 Nov 2022

DOMDocument replace occurrence of text in nodeValue with <a> link

function replace_text_with_anchor($domDocument, $searchFor, $replaceWith, $url) { $query = "//text()[contains(., '" . $searchFor . "')]"; $xpath = new DOMXPath($domDocument); $textNodes = $xpath->query($query); foreach ($textNodes as $node) { $fragment = $domDocument->createDocumentFragment(); $fragment->appendXML("<a href=\"" . $url . "\">" . $replaceWith . "</a>"); $node->parentNode->replaceChild($fragment, $node); } }

Questions about programming?Chat with your personal AI assistant