2013-03-26 76 views
1

我解析HTML中的PHP和我无法控制的原始内容我想剥夺它的样式和不必要的标签,同时仍然保持内容和标签的短名单,分别是:我怎样才能删除所有的标记,除了从PHP解析的HTML允许列表中删除PHP

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'); 
+3

奇怪的是,有一个名为strip_tags的函数已经内置到PHP中。 http://www.php.net/manual/en/function.strip-tags.php – 2013-03-26 02:21:31

+0

哦,亲爱的:(一个经典的隧道视觉案例,我应该先考虑过这个方法。 – Finglish 2013-03-26 08:07:30

回答

5

所讲的上述cpattersonv1,你可以简单地使用strip_tags()作业。

<?php 

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

?> 
相关问题