1

我在 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');
4

1 回答 1

5

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

<?php

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

?>
于 2013-03-26T02:27:22.380 回答