How can I replace strings NOT within a link tag?

后端 未结 3 1802
我在风中等你
我在风中等你 2020-12-06 20:43

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

3条回答
  •  粉色の甜心
    2020-12-06 21:11

    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.

提交回复
热议问题