How to replace node with string using DOMDocument

Possible duplicate:
PHP - How to replace a phrase with another?

I need to convert this html piece

<html> <body> Lorum ipsum <a href="http://google.com">click here</a> dolores lorem. Lorum ipsum <a href="http://stackoverflow.com">click here too</a> dolores lorem. </body> </html> 

To:

 <html> <body> Lorum ipsum @@ 1@ @ dolores lorem. Lorum ipsum @@ 2@ @ dolores lorem. </body> </html> 

How can this be achieved with Domdocument (I'm not interested in een regex solution)?

+4
source share
1 answer

You havenโ€™t provided any code yet, so itโ€™s actually not clear what problem you are running into. I can only assume that this is because if you iterate over the list of links modifying it, then the iteration becomes invalid. Thus, only the first element is replaced.

Using a for loop can help here to get only the first element for each iteration. It would also allow you to initialize and increase the count variable for the numbers you need in the replacement.

Replacement itself can be easily done with replaceChild . Example loop:

 for($c = 1; $a = $doc->getElementsByTagName('a')->item(0); $c++) { $a->parentNode->replaceChild( $doc->createTextNode(sprintf("@@% d@ @", $c)), $a ); } 

Calling $doc->getElementsByTagName('a')->item(0) will return NULL if such an item does not exist (anymore). This is a loop exit condition.

Full example:

 $html = '<html><body> Lorum ipsum <a href="http://google.com">click here</a> dolores lorem. Lorum ipsum <a href="http://stackoverflow.com">click here too</a> dolores lorem. </body></html>'; $doc = new DOMDocument(); $doc->loadHtml($html); for($c = 1; $a = $doc->getElementsByTagName('a')->item(0); $c++) { $a->parentNode->replaceChild( $doc->createTextNode(sprintf("@@% d@ @", $c)), $a ); } echo $doc->saveHTML(); 

Output:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body> Lorum ipsum @@ 1@ @ dolores lorem. Lorum ipsum @@ 2@ @ dolores lorem. </body></html> 

I hope this will be helpful.

+4
source

Source: https://habr.com/ru/post/1444536/


All Articles