Carl Barrett Carl Barrett - 1 year ago 96
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:

So for, here's what I did in approaching the code as a newbie to DOM.

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;

$search = 'FirstName lastname';
$replace = 'Jack Daniels';

$newTxt = domTextReplace( $search, $replace, DOMNode &$doc, $isRegEx = false );

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

Answer Source

Here you have a working example to use that function:


$myXmlString = '<root><name>FirstName lastname</name></root>';

$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;

$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");

// 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:

  <name>Jack Daniels</name>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download