I try to replace links in a HTML string to a text but because I replace the source inside the iteration I get weird mixed results. Any idea how to solve this:
$body='<a href="link1">text1</a> and <a href="link2">text2</a> and <a href="link3">text3</a>';
$dom = new DOMDocument();
$dom->loadHTML($body);
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor) {
$link = $anchor->getAttribute('href');
$text = $anchor->nodeValue;
$new = $dom->createTextNode($text."
".$link."
");
$anchor->parentNode->replaceChild($new,$anchor);
echo($text); //debug
}
$body_plain = $dom->saveHTML();
It has to become:
text1
link1
and
text2
link2
and
text3
link3
But instead the second link will not be replaced. When debugging it skips the second link:
text1
link1 and <a href="link2">text2</a> and
text3
link3
Any help appreciated.