替换DOM中的标签

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.

getElementsByTagName produces a live list of nodes. After replacing the first link with its text, the code then looks for the second link in the resulting DOM, which is the third link in the original.

Personally, I prefer to use XPath even for simple things:

$xpath = new DOMXPath($dom);
$anchors = $xpath->query("//a");

This will work ;)