0

我需要加载一个 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>
4

3 回答 3

3

无法获得足够的 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;
}
于 2012-06-08T14:35:11.843 回答
0

您可以使用简单的 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;
于 2012-06-08T14:38:03.703 回答
0

如果您想尝试正则表达式,请查看此答案replace all "foo" between two HTML tags using REGEX (PHP code)

于 2012-06-08T14:41:52.290 回答