Strip HTML tags and its contents

旧街凉风 提交于 2019-11-27 14:22:55
Lukáš Lalinský

Try removing the spans directly from the DOM tree.

$dom = new DOMDocument();
$dom->loadHTML($string);
$dom->preserveWhiteSpace = false;

$elements = $dom->getElementsByTagName('span');
while($span = $elements->item(0)) {       
   $span->parentNode->removeChild($span);
}

echo $dom->saveHTML();

@ile - I've had that problem - it's because the index of the foreach iterator happily keeps incrementing, while calling removeChild() on the DOM also seems to remove the nodes from the DomNodeList ($spans). So for every span you remove, the nodelist shrinks one element and then gets its foreach counter incremented by one. Net result: it skips one span.

I'm sure there is a more elegant way, but this is how I did it - I moved the references from the DomNodeList to a second array, where they would not be removed by the removeChild() operation.

    foreach($spans as $span) {
        $nodes[] = $span;
    }
    foreach($nodes as $span) {
        $span->parentNode->removeChild($span);
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!