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

后端 未结 1 1289
天涯浪人
天涯浪人 2020-12-07 02:43

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 t

相关标签:
1条回答
  • 2020-12-07 03:26

    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());
    
    0 讨论(0)
提交回复
热议问题