PHP DOM文本替换


PHP DOM Text Replace

我需要在动态做PHP DOM文本替换一点帮助。在我的研究中,我发现了一段看起来很有前途的PHP DOM代码,但是作者没有提供有关其工作原理的方法。代码的链接是:http://be2.php.net/manual/en/class.domtext.php

所以,这是我作为一个DOM新手所做的。

    $doc = new DOMDocument();
    $doc->preserveWhiteSpace = false;
    $doc->loadXML($myXmlString);
    $search = 'FirstName lastname';  
    $replace = 'Jack Daniels';      
    $newTxt = domTextReplace( $search, $replace, DOMNode &$doc, $isRegEx = false );
    Print_r($newTxt);

我希望domTextReplace()返回$newTxt。我怎样才能让它这样做呢?

这里有一个使用该函数的工作示例:

<?php
$myXmlString = '<root><name>FirstName lastname</name></root>';
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML($myXmlString);
$search = 'FirstName lastname';
$replace = 'Jack Daniels';
// The function doesn't return any value
domTextReplace($search, $replace, $doc, $isRegEx = false);
// Now the text is replaced in $doc
$xmlOutput = $doc->saveXML();
// I put xml header to display the results correctly on the browser
header("Content-type: text/xml");
print_r($xmlOutput);
// I copied here the function for everyone to find it quick
function domTextReplace( $search, $replace, DOMNode &$domNode, $isRegEx = false ) {
  if ( $domNode->hasChildNodes() ) {
    $children = array();
    // since looping through a DOM being modified is a bad idea we prepare an array:
    foreach ( $domNode->childNodes as $child ) {
      $children[] = $child;
    }
    foreach ( $children as $child ) {
      if ( $child->nodeType === XML_TEXT_NODE ) {
        $oldText = $child->wholeText;
        if ( $isRegEx ) {
          $newText = preg_replace( $search, $replace, $oldText );
        } else {
          $newText = str_replace( $search, $replace, $oldText );
        }
        $newTextNode = $domNode->ownerDocument->createTextNode( $newText );
        $domNode->replaceChild( $newTextNode, $child );
      } else {
        domTextReplace( $search, $replace, $child, $isRegEx );
      }
    }
  }
}

输出:

<root>
  <name>Jack Daniels</name>
</root>