Carl Barrett Carl Barrett - 1 month ago 14
PHP Question

PHP DOM Text Replace

I need a little help in dynamically doing PHP DOM text replacement. In my research, I found a snippet of PHP DOM code that looks promising, but the writer provides no method as to how it works. The link to the code is: http://be2.php.net/manual/en/class.domtext.php

So for, here's what I did in approaching the code as a newbie to 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);


I would like the
domTextReplace()
return $newTxt. How can I get it to do so?

Answer

Here you have a working example to use that function:

<?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 );
      }
    }
  }
}

This is the output:

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