替换 html 内容而不替换标签或属性 - PHP

Replace html content without replacing the tags or attributes - PHP

如何在不替换 HTML 标签或属性的情况下替换 HTML dom 内部或外部的内容?

例如

$txt='good <div class="good">good</div>'
$search='good';
$pattern      = '#(?!<.*?)(\b'.$search.'\b)(?![^<>]*?>)#si'; 
$replacement  = 'nice';
$txt = preg_replace($pattern, $replacement, $txt);

所以我希望它输出 nice <div class="good">nice</div> 并忽略任何属性中的 good 因为标签和属性是我不知道的动态,这只是示例。

尝试使用 dom:

$txt='good <div class="good">good</div>';
$search = 'good';
$replace  = 'nice';

libxml_use_internal_errors(true);
$dom = new DomDocument();
$dom->loadHTML($txt, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);

foreach ($xpath->query('//text()') as $text) {
    if (trim($text->nodeValue)) {
        $text->nodeValue = str_replace($search,$replace, $text->nodeValue);
   }
}
echo $dom->saveHTML();