2011-07-22 47 views
2

如何去除某些html标签并允许其中的一些?strip_tags:去掉乱七八糟的标签和样式

例如,

我要脱光span标签,但允许span用下划线。

<span style="text-decoration: underline;">Text</span> 

我想允许p但我想删除任何样式或类p例如内,

<p class="99light">Text</p> p标签里面的类应除去 - 我只是想要一个干净的p标签。

的是我到目前为止线,

strip_tags($content, '<p><a><br><em><strong><ul><li>'); 
+1

使用DOM解析器。 – webbiedave

+0

http://htmlpurifier.org/ –

+1

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – naveen

回答

1

你不能。您需要使用XML/HTML解析器来执行此操作:

// with DOMDocument it might look something like this. 
$dom = new DOMDocument(); 
$dom->loadHTML($content); 
foreach($dom->getElementsByTagName("p") as $p) 
{ 
    // removes all attributes from a p tag. 
    /* 
    foreach($p->attributes as $attrib) 
    { 
     $p->removeAttributeNode($attrib); 
    } 
    */ 
    // remove only the style attribute. 
    $p->removeAttributeNode($p->getAttributeNode("style")); 
} 
echo $dom->saveHTML(); 
0

你需要完整的DOM解析。 strip_tags将不提供必要的安全性和定制。我过去为此使用了HTMLPurifier库。它实际解析并允许您设置白名单,同时照顾恶意输入并生成有效标记! “必要的安全性”我的意思是,如果你尝试写一个自定义的解析器,你会犯一个错误(不要担心,我也会),通过“定制”我的意思是没有内置的解决方案会让你只针对某些具有某些属性和这些属性值的标签。 HTMLPurifier是PHP库解决方案。