[英]PHP DomDocument - How to replace a text from a Node with another node
我有一個節點:
<p>
This is a test node with Figure 1.
</p>
我的目標是用一個子節點替換“圖1”:
<xref>Figure 1</xref>
這樣最終結果將是:
<p>
This is a test node with <xref>Figure 1</xref>.
</p>
先感謝您。
Xpath允許您從文檔中獲取包含字符串的文本節點。 然后,您必須將其拆分為文本和元素(xref)節點的列表,並將該節點插入文本節點之前。 最后刪除原始文本節點。
$xml = <<<'XML'
<p>
This is a test node with Figure 1.
</p>
XML;
$string = 'Figure 1';
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
// find text nodes that contain the string
$nodes = $xpath->evaluate('//text()[contains(., "'.$string.'")]');
foreach ($nodes as $node) {
// explode the text at the string
$parts = explode($string, $node->nodeValue);
// add a new text node with the first part
$node->parentNode->insertBefore(
$dom->createTextNode(
// fetch and remove the first part from the list
array_shift($parts)
),
$node
);
// if here are more then one part
foreach ($parts as $part) {
// add a xref before it
$node->parentNode->insertBefore(
$xref = $dom->createElement('xref'),
$node
);
// with the string that we used to split the text
$xref->appendChild($dom->createTextNode($string));
// add the part from the list as new text node
$node->parentNode->insertBefore(
$dom->createTextNode($part),
$node
);
}
// remove the old text node
$node->parentNode->removeChild($node);
}
echo $dom->saveXml($dom->documentElement);
輸出:
<p>
This is a test node with <xref>Figure 1</xref>.
</p>
您可以首先使用getElementsByTagName()
查找要查找的節點,然后從該節點的nodeValue
中刪除搜索文本。 現在,創建新節點,將nodeValue
設置為搜索文本,並將新節點附加到主節點:
<?php
$dom = new DOMDocument;
$dom->loadHTML('<p>This is a test node with Figure 1</p>');
$searchFor = 'Figure 1';
// replace the searchterm in given paragraph node
$p_node = $dom->getElementsByTagName("p")->item(0);
$p_node->nodeValue = str_replace($searchFor, '', $p_node->nodeValue);
// create the new element
$new_node = $dom->createElement("xref");
$new_node->nodeValue = $searchFor;
// append the child element to paragraph node
$p_node->appendChild($new_node);
echo $dom->saveHTML();
輸出:
<p>This is a test node with <xref>Figure 1</xref></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.