PHP function to strip tags, except a list of whitelisted tags and attributes

佐手、 提交于 2019-12-17 17:13:59

问题


I have to strip all HTML tags and attributes from a user input except the ones considered "safe" (ie, a white list approach).

strip_tags() strips all tags except the ones listed in the $allowable_tags parameter. But I also need to be able to strip all the not whitelisted attributes; for example, I want to allow the <b> tag, but I don't want to allow the onclick attribute for obvious reasons.

Is there a function to do that, or will I have to make my own?


回答1:


As far as I know, the strip_tags solution is about the fastest way to get rid of unwanted tags, and barring 3rd party packages, checking for allowable attributes would be quite easy in DOMDocument,

$string = strip_tags($string,'<b>');
$dom = new DOMDocument();
$dom->loadHTML($string);
$allowed_attributes = array('id');
foreach($dom->getElementsByTagName('*') as $node){
    for($i = $node->attributes->length -1; $i >= 0; $i--){
        $attribute = $node->attributes->item($i);
        if(!in_array($attribute->name,$allowed_attributes)) $node->removeAttributeNode($attribute);
    }
}
var_dump($dom->saveHTML());



回答2:


There is no function for that, so you will probably have to write one. Perhaps, a regular expression will do the trick.



来源:https://stackoverflow.com/questions/3387445/php-function-to-strip-tags-except-a-list-of-whitelisted-tags-and-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!