I am working on this PHP function. The idea is to wrap certain words occuring in a string into certain tags (both, words and tags, given in an array). It works OK!, but when
Use the DOM and only modify text nodes:
$s = "foo foo lorem bar ipsum foo. bar not a test";
echo htmlentities($s) . '
';
$d = new DOMDocument;
$d->loadHTML($s);
$x = new DOMXPath($d);
$t = $x->evaluate("//text()");
$wrap = array(
'foo' => 'h1',
'bar' => 'h2'
);
$preg_find = '/\b(' . implode('|', array_keys($wrap)) . ')\b/';
foreach($t as $textNode) {
if( $textNode->parentNode->tagName == "a" ) {
continue;
}
$sections = preg_split( $preg_find, $textNode->nodeValue, null, PREG_SPLIT_DELIM_CAPTURE);
$parentNode = $textNode->parentNode;
foreach($sections as $section) {
if( !isset($wrap[$section]) ) {
$parentNode->insertBefore( $d->createTextNode($section), $textNode );
continue;
}
$tagName = $wrap[$section];
$parentNode->insertBefore( $d->createElement( $tagName, $section ), $textNode );
}
$parentNode->removeChild( $textNode );
}
echo htmlentities($d->saveHTML());
Edited to replace DOMText with DOMText and DOMElement as necessary.