removeNode 无法正常工作

removeNode doesn't work correctly

我想删除所有以“/”开头的锚标签。这是我的代码:

$html = <<<HTML
<ul>
  <li><a href="/foo/bar1">link1</li>
  <li><a href="/foo/bar2">link2</li>
  <li><a href="/foo/bar3">link3</li>
</ul>
HTML;

$dom = new DOMDocument;
@$dom->loadHTML($html);
$tags = $dom->getElementsByTagName('a');
echo 'removed nodes:<br />';
foreach ($tags as $tag)
{
    $href = $tag->getAttribute('href');
    if($href[0] == '/')
    {
        echo $tag->nodeValue.'<br />';
        $tag->parentNode->removeChild($tag);
    }
}
echo 'remined content:<br />';
echo $dom->saveXML($dom);

但问题是它提醒了他们中的一些人。

removed nodes:<br>
link1<br>
link3<br>

remined content:<br>
<ul><li>
  </li><li><a href="/foo/bar2">link2</a></li>
  <li>
</li></ul>

知道怎么做吗? 谢谢。

您无法从 DOMNodeList 中删除 DOMNode,因为您在 foreach 循环中对其进行迭代 (http://php.net/manual/en/domnode.removechild.php#90292)。不过,制作要删除的项目队列似乎可行:

<?php
$html = <<<HTML
<ul>
  <li><a href="/foo/bar1">link1</a></li>
  <li><a href="/foo/bar2">link2</a></li>
  <li><a href="/foo/bar3">link3</a></li>
</ul>
HTML;

$dom = new DOMDocument;
@$dom->loadHTML($html);


$domNodeList = $dom->getElementsByTagName('a'); 
$domElemsToRemove = array(); 
foreach ($domNodeList as $domElement ) { 
  $domElemsToRemove[] = $domElement; 
} 
echo 'removed nodes:<br />';
foreach ($domElemsToRemove as $tag)
{
    $href = $tag->getAttribute('href');
    if($href[0] == '/')
    {
        echo $tag->nodeValue.'<br />';
        $tag->parentNode->removeChild($tag);
    }
}
echo 'remined content:<br />';
echo $dom->saveXML($dom);

编辑

你也忘了关闭标签<a>