在 HTML 中用另一个字符串替换一个字符串,但在 HTML 标记和属性 PHP 中没有


Replace a string with another in HTML but no in HTML tags and attributes PHP

我需要加载一个HTML(也许使用DOMDocument loadHTML),然后将所有单词A替换为单词B,但html标签内没有任何内容。

这意味着在下面的html中,如果我们需要将单词"test"替换为"TEST",它只会将文本"This is a test"替换为"this is a test",并保持id="test"不变

<html>
<head></head>
<body>
  <div id="test"> this is a test </div>
</body>
</html>

无法获得足够的 DOMDocument :)

$d = new DOMDocument;
$d->loadHTML($html);
$x = new DOMXPath($d);
foreach ($x->query('//text()') as $node) {
    $node->nodeValue = str_replace('test', 'TEST', $node->nodeValue);
}
echo $d->saveHTML();

不确定总是在nodeValue上执行替换是否有任何性能损失;否则,将循环内容替换为:

$s = str_replace('test', 'TEST', $node->nodeValue, $count);
if ($count) {
    $node->nodeValue = $s;
}

您可以使用Simple html dom解析器:

include("simple_html_dom.php");
...
$html = '
<html>
 <head></head>
 <body>
  <div id="test"> this is a test </div>
 </body>
</html>
';
$data = str_get_html($html);
$find = $data->find("div[id='test']",0);
$find->innertext = str_replace("test","TEST",$find->innertext);
$data = $data->save();
echo $data;