PHP DomDocument-如何用另一个节点替换一个节点中的文本


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>

演示