gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:18:42 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com