DOMDocument replace text in nodeValue with <a> link
function replaceText($document, $text) { $xpath = new DOMXpath($document); foreach($xpath->query('//text()') as $node) { $fragment = $document->createDocumentFragment(); $fragment->appendXML( preg_replace( '/' . $text . '+/', '<a href="https://google.com">' . $text . '</a>', $node->nodeValue ) ); $node->parentNode->replaceChild($fragment, $node); } }