DOMDocument长度更改后,foreach停止

I've got a problem with a forach loop and replaceChild, because when i replace the Child for which the foreach is looping through it stops. How can I prevent this behaviour ?

Here is the Code i have;

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($this->template);
foreach ($dom->getElementsByTagName("func") as $pnode) {
  echo "CALLED!";
  $attr = $pnode->getAttribute('type');
  $function = $pnode->nodeValue;
  if (array_key_exists($function, parent::$located_functions)) {
    $arr = parent::$located_functions[$function];
    if (class_exists($arr[1])) {
      $call = $arr[1]::$arr[0]();
      $divnode = $dom->createElement("div");
      $this->addHTML($divnode, $call);
      $pnode->parentNode->replaceChild($divnode, $pnode);
      echo "LNG: " . $dom->getElementsByTagName("func")->length;
      $this->template = $dom->saveXML($pnode->parentNode);
    }
  }
}

Before I start the script "$dom->getElementsByTagName("func")->length" is 2, "LNG:" gives me 1 after the replaceChild (because I replaced it with HTML Code from $call). Now the loop seems to stop (maybe he thinks that he allready looped through, because the length is now 1 and he is at length 1). If I don't call replaceChild it will work as expected, but with replaceChild it doesn't work. "Called" is also only displayed once, so the if-clauses shouldn't be the Problem.

But how can I prevent this?