With this code using DomDocument:
<?php
$html = '<pre>one</pre><pre>two</pre><pre>three</pre><pre>four</pre>';
$doc = new DomDocument();
$doc->loadHTML($html);
$sub = $doc->getElementsByTagName("pre");
foreach($sub as $pre) {
$fragment = $doc->createDocumentFragment();
$fragment->appendXML(str_replace('&', '&', '<p>& it\'s replaced</p>'));
$pre->parentNode->replaceChild($fragment, $pre);
}
echo $doc->saveHTML();
?>
I get this output:
<p>& it's replaced</p>
<pre>two</pre>
<p>& it's replaced</p>
<pre>four</pre>
Can someone explain to me what is going on and why all the pre tags aren’t being replaced?
You can try this way: http://codepad.viper-7.com/ALYWEi
I found the issue when I googled “DomDocument replacechild” without the quotes
see the first comment here: http://php.net/manual/en/domnode.replacechild.php particularly this: