小编use*_*657的帖子

尝试使用 PHP DOM 替换节点文本而不更改子节点

我正在尝试使用 dom 对象来简化词汇表工具提示的实现。我需要做的是替换段落中的文本元素,但不是替换可能嵌入段落中的锚标记。

$html = '<p>Replace this tag not this <a href="#">tag</a></p>';
$document = new DOMDocument();
$document->loadHTML($html);
$document->preserveWhiteSpace = false;
$document->validateOnParse = true;

$nodes = $document->getElementByTagName("p");
foreach ($nodes as $node) {
  $node->nodeValue = str_replace("tag","element",$node->nodeValue);
}
echo $document->saveHTML();
Run Code Online (Sandbox Code Playgroud)

我得到:

'...<p>Replace this element not this element</p>...'
Run Code Online (Sandbox Code Playgroud)

我想:

'...<p>Replace this element not this <a href="#">tag</a></p>...'
Run Code Online (Sandbox Code Playgroud)

如何实现这一点,以便仅更改父节点文本而不更改子节点(标签)?

php dom domdocument

4
推荐指数
1
解决办法
2678
查看次数

标签 统计

dom ×1

domdocument ×1

php ×1