Regex / DOMDocument - match and replace text not in a link

后端 未结 7 1121
轮回少年
轮回少年 2020-12-01 07:06

I need to find and replace all text matches in a case insensitive way, unless the text is within an anchor tag - for example:

Match this text and re

7条回答
  •  离开以前
    2020-12-01 07:32

    Try this one:

    $dom = new DOMDocument;
    $dom->loadHTML($html_content);
    
    function preg_replace_dom($regex, $replacement, DOMNode $dom, array $excludeParents = array()) {
      if (!empty($dom->childNodes)) {
        foreach ($dom->childNodes as $node) {
          if ($node instanceof DOMText && 
              !in_array($node->parentNode->nodeName, $excludeParents)) 
          {
            $node->nodeValue = preg_replace($regex, $replacement, $node->nodeValue);
          } 
          else
          {
            preg_replace_dom($regex, $replacement, $node, $excludeParents);
          }
        }
      }
    }
    
    preg_replace_dom('/match this text/i', 'IT WORKS', $dom->documentElement, array('a'));
    

提交回复
热议问题