PHP Filter HTML tag attribute class

Source: Internet
Author: User

PHP Filter HTML tag attribute class


HtmlAttributeFilter.class.php

<?php/** HTML Attribute filter* date:2013-09-22* author:fdipzone* ver:1.0** func:* public strip Filter Properties * Public Setallow settings allowed properties * Public setexception Settings Exceptions * Public setignore settings ignored Tag * Private findelements search for elements to be processed * Private findattributes Search Property * Private Removeattributes Remove attribute * privat E isexception Judge If the exception is private createattributes Create attribute * Private protect special character escapes */class Htmlattributefi            lter{//class start private $_str = ';     SOURCE string Private $_allow = Array (); Allow reserved properties such as: Array (' ID ', ' class ', ' title ') Private $_exception = Array ();    Exceptions For example: Array (' A ' =>array (' href ', ' class '), ' span ' =>array (' class ')) Private $_ignore = Array ();  Ignore filtered tags such as: Array (' span ', ' img ')/** processing HTML, filtering properties not reserved * @param string $str Source String * @return String */Public        function strip ($str) {$this->_str = $str; if (is_string ($this->_str) && strlen ($thiS-&GT;_STR) {//>0) {//judgment string $this->_str = Strtolower ($this->_str);//Turn lowercase $res = $this->fi            Ndelements ();            if (is_string ($res)) {return $res;            } $nodes = $this->findattributes ($res);        $this->removeattributes ($nodes);    } return $this->_str; }/** set the allowed properties * @param Array $param */Public Function Setallow ($param =array ()) {$this->_allow = $pa    Ram }/** Set Exception * @param Array $param */Public Function setexception ($param =array ()) {$this->_exception    = $param; }/** set the ignored tag * @param Array $param */Public Function Setignore ($param =array ()) {$this->_ignore = $    Param        /** search for the element to be processed */Private Function findelements () {$nodes = array ();        Preg_match_all ("/<" ([^!\/\>\n]+) ([^>]*) >/i ", $this->_str, $elements); foreach ($elements [1] as $el _key + = $element) {if ($elements[2][$el _key]) {$literal = $elements [0][$el _key];                $element _name = $elements [1][$el _key];                $attributes = $elements [2][$el _key]; if (Is_array ($this->_ignore) &&!in_array ($element _name, $this->_ignore)) {$nodes [] = Arra                Y (' literal ' = $literal, ' name ' = $element _name, ' attributes ' + $attributes);        }}} if (! $nodes [0]) {return $this->_str;        }else{return $nodes; }}/** Search properties * @param Array $nodes The element to be processed */Private function findattributes ($nodes) {foreach ($nod Es as & $node) {Preg_match_all ("/([^ =]+) \s*=\s*[\" |] {0,1} ([^\"']*) [\"|']            {0,1}/i ", $node [' Attributes '], $attributes); if ($attributes [1]) {foreach ($attributes [1] as $att _key=> $att) {$literal = $attributes [0]                    [$att _key]; $attribute _name = $attributes [1][$att _key];                   $value = $attributes [2][$att _key];                $atts [] = Array (' literal ' = $literal, ' name ' = = $attribute _name, ' value ' = $value);            }}else{$node [' attributes '] = NULL;            } $node [' attributes '] = $atts;        Unset ($atts);    } return $nodes; /** Remove attribute * @param Array $nodes The element to be processed */Private function removeattributes ($nodes) {foreach ($nodes            As $node) {$node _name = $node [' name '];            $new _attributes = "; if (Is_array ($node [' attributes '])) {foreach ($node [' attributes '] as $attribute) {if (Is_ar Ray ($this->_allow) && in_array ($attribute [' name '], $this->_allow)) | | $this->isexception ($node _name, $attribute [' name '], $this->_exception)) {$  New_attributes = $this->createattributes ($new _attributes, $attribute [' name '], $attribute [' value '];                  }}} $replacement = ($new _attributes)?            "< $node _name $new _attributes>": "< $node _name>"; $this->_str = preg_replace ('/'. $this->protect ($node [' literal ']). '        /', $replacement, $this->_str); }}/** to determine if the exception is * @param string $element _name element name * @param string $attribute _name property name * @param Array $exc         Eptions Allowed Exceptions * @return Boolean */Private Function isexception ($element _name, $attribute _name, $exceptions) { if (array_key_exists ($element _name, $this->_exception)) {if (In_array ($attribute _name, $this->_exce            ption[$element _name]) {return true;    }} return false;     /** Create Property * @param string $new _attributes * @param string $name * @param string $value * @return string */Private Function createattributes ($new _attributes, $name, $value) {if ($new _attributes) {$new _a Ttributes.= " ";        } $new _attributes. = "$name =\" $value \ "";    return $new _attributes; /** special Character escapes * @param string $str Source String * @return String */Private Function Protect ($STR) {$convers ions = Array ("^" = "\^", "[" = "=" \[",". "=" \. "," $ "and" = "\$             "," {"=" \{"," * "and" \* "," ("=" \ "," \ \ "=" \\\\ ", "/" = "/", "+" = "\+", ")" = "\", "|" = "\|", "?        "= =" \ "," < "=" \< "," > "and" \> ");    Return Strtr ($str, $conversions); }}//Class end?>

demo

<?phprequire (' HtmlAttributeFilter.class.php '); $str = ' <p class= ' BD Clearfix "id=" Index_hilite_ul "><ul class=" list "><li><p class=" cover "><a class=" text "href=" </a>< Strong class= "T G" >want to Know</strong><a href= "/login.html" class= "ppbtn" ><strong class= "text" >YES</strong></a></p></li></ul></p> '; $obj = new Htmlattributefilter ();//  Allow ID attribute $obj->setallow (array (' ID ')), $obj->setexception (Array (' a ' = = Array (' href '),//a tag allows HREF attribute special case ' ul ' = = Array (' class ')//UL tag allows a special case of class attribute);//img tag Ignore, do not filter any attributes $obj->setignore (ARRA Y (' img ')); Echo ' source str:<br> '; Echo htmlspecialchars ($str). ' <br><br> '; Echo ' filter str:<br> '; Echo htmlspecialchars ($obj->strip ($STR));? 


The above is the PHP filter HTML tag attribute class content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.