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

标签 php dom domdocument

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

$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();

我得到:

'...<p>Replace this element not this element</p>...'

我要:

'...<p>Replace this element not this <a href="#">tag</a></p>...'

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

最佳答案

试试这个:

$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->getElementsByTagName("p");

foreach ($nodes as $node) {
    while( $node->hasChildNodes() ) {
        $node = $node->childNodes->item(0);
    }
    $node->nodeValue = str_replace("tag","element",$node->nodeValue);
}
echo $document->saveHTML();

希望这对您有所帮助。

更新 要在下面的评论中回答@paul 的问题,您可以创建

$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->getElementsByTagName("p");

//create the element which should replace the text in the original string
$elem = $document->createElement( 'dfn', 'tag' );
$attr = $document->createAttribute('title');
$attr->value = 'element';
$elem->appendChild( $attr );

foreach ($nodes as $node) {
    while( $node->hasChildNodes() ) {
        $node = $node->childNodes->item(0);
    }
    //dump the new string here, which replaces the source string
    $node->nodeValue = str_replace("tag",$document->saveHTML($elem),$node->nodeValue);
}
echo $document->saveHTML();

关于php - 尝试使用 PHP DOM 替换节点文本而不更改子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13927248/

相关文章:

java - XML 文档转换 StackOverflowError

javascript - 确定事件冒泡通过的元素

javascript - 为什么我在这里得到的 document.getElementById 为 null?

php - 我可以有一个只接受从 AJAX 调用绑定(bind)的新变量的持久 PDO 对象吗?

javascript - 在 React 中实现硬重载

java - 这会通过标签名称 "c"获取元素吗?在我的程序中它不起作用?

php DOMDocument - 操作和编码

javascript - Bootstrap 模式不适用于实时服务器

php - 从 WooCommerce 购物车错误消息中删除库存数量

javascript - 这两个 promise 和我期望发生的事情之间的区别