generate functionMon, 07 Nov 2022

DOMDocument replace text with link

function replace_text_with_link($dom, $text, $link){ $query = new DOMXPath($dom); $nodeList = $query->query("//text()[contains(., '".$text."')]"); foreach ($nodeList as $node) { $span = $dom->createElement('span', $node->nodeValue); $a = $dom->createElement('a', $text); $a->setAttribute('href',$link); if(!$node->parentNode->getAttribute('href') && !$node->parentNode->getAttribute('href')){ $node->parentNode->replaceChild($a, $node); $a->appendChild($span); } } return $dom; }

Questions about programming?Chat with your personal AI assistant