generate functionMon, 07 Nov 2022

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); } }

Questions about programming?Chat with your personal AI assistant