2013-12-13 30 views

回答

2

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> 
1

您可以先使用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> 

Demo.

+0

我重新打開了這個問題,因爲代碼不會真的取代了節點給定文本:創建節點總是在$段落節點的末尾添加的,所以如果我在圖1之後添加了一些東西,那麼代碼不再工作。 –

相關問題