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

Want to kickstart your project?Use the new AI Studio to create your code