我如何删除所有的标签,除了允许列表从 html解析php


How can I remove all tags except an allowed list from html parsed by php

我在php中解析html,因为我无法控制原始内容,我想剥离它的样式和不必要的标签,同时仍然保留内容和标签的短列表,即:

p, img, iframe(可能还有其他几个)

我知道我可以删除一个给定的标签(见下面我使用的代码),但因为我不一定知道他们可能是什么标签,我不想创建一个巨大的可能列表,我希望能够剥离除我允许的列表之外的所有内容。

function DOMRemove(DOMNode $from) {
    $sibling = $from->firstChild;
    do {
        $next = $sibling->nextSibling;
        $from->parentNode->insertBefore($sibling, $from);
    } while ($sibling = $next);
    $from->parentNode->removeChild($from);
}
$dom = new DOMDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('span');

正如上面cpattersonv1所说,您可以简单地使用strip_tags()来完成作业。

<?php
// strip all other tags except mentioned (p, img, iframe)
$html_result = strip_tags($html, '<p><img><iframe>');
?>