PHP Filter HTML tag attribute Class usage Example

Source: Internet
Author: User
Tags foreach php class

The specific methods are as follows:

The HtmlAttributeFilter.class.php class files are as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179-18 0 181 182 183 184 185 186 187 188 189 190 <?php /** HTML Attribute filter  *  date:  2013-09-22  *  author:fdipzone  ; ver:  1.0  *  *  func:  *  public strip       Filter Properties   *& nbsp Public setallow      settings allowed properties   *  public setexception    settings special case   *  public setignore     settings ignored tags   *  private findelements    Search for elements to be processed   *  private findattributes   Search properties   *  private removeattributes  removal properties   *  Private isexception    judge whether special case   *  private createattributes  Create attribute   *& nbsp Private protect      special character escape   */      class htmlattributefilter{// Class start        private $_str = ';     //source string      private $_allow = Array ();  //Allow securityLeft attributes such as: Array (' ID ', ' class ', ' title ')     private $_exception = Array (); Exceptions such as: Array (' A ' =>array (' href ', ' class '), ' span ' =>array (' class '))     private $_ignore = Array () ; //Ignore filtered tags For example: Array (' span ', ' img ')             /** processing HTML, filtering properties that are not retained     * @param string $str source string     * @return string    */     Public function strip ($STR) {       $this->_str = $str;           if (is_string ($this->_str) && strlen ($this->_str) >0) {//judgment string               $this->_str = strtolower ($this->_str); Convert to lowercase              $res = $this->findelements ();         if (is_string ($res)) {          return $res;   &NBsp;    }         $nodes = $this->findattributes ($res);          $this->removeattributes ($nodes);      }       return $this->_str;    }        /** Set allowed properties     * @param Array $param     */    public function Setallow ($param =array ()) {       $this->_allow = $param;    }        /** Settings Special case     * @param Array $param     */    public function SetException ($param =array ()) {       $this->_exception = $param;             /** settings ignored tags     * @param Array $param     */  & Nbsp; public function Setignore ($param =array ()) {       $this->_ignore = $param;    }        /** Search for elements 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[] = array (' literal ' => $literal, ' name ' => $element _namE, ' attributes ' => $attributes);          }         }      }          if (!$ Nodes[0]) {        return $this->_str;      }else{         return $nodes;      }    }         /** Search Properties     * @param Array $nodes elements to be processed     */     private function findattributes ($nodes) {      foreach ($nodes 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) {    & nbsp;        $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;    }        /** Removal properties     * @param Array $nodes elements that need to be processed &NBSP   */    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_array ($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 ']);           &nbsp}           }        }         $replacement = ($new _attributes)? "< $node _name $new _attributes>": "< $node _name>";         $this->_ str = preg_replace ('/'. $this->protect ($node [' literal ']). ' /', $replacement, $this->_str);      }    }        /** judge whether the special case     * @param string $element _name  element name     * @param string $ Attribute_name Property name     * @param Array $exceptions    permitted exceptions     * @return boolean& nbsp   */    private function isexception ($element _name, $attribute _name, $exceptions) {      if (array_key_exists ($element _name, $this->_exception)) {         if (In_array ($attribute _name, $this->_exception[$element _name]) {           return true;        }      }       return false;    }        /** Create properties     * @param String $new _ attributes    * @param string $name     * @param String $value     * @return S tring    */    private function createattributes ($new _attributes, $name, $value) {       if ($new _attributes) {         $new _attributes. = " ";      }       $new _attributes. =" $name = "$value" ";       return $new _attributes;    }             /** special character escape     * @param String $str source string     * @return string    */& nbsp   private function Protect ($STR) {       $conversions = Array (         "^" => "^",           ["=>" [",         ". "=>". ",           "$" => "$",          "{" => "{",           "*" => "*",          "(" => "(",          "" => "",          "/" => "/",          "+" => "+",           ")" => ")",          | "=>" | ",           "=>"? ",         " < "=>" < ",           ">" => ">"        );      return strtr ($str, $conversions);    }      }//class end     ?>

The

Demo sample code is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?php  require (' HtmlAttributeFilter.class.php ');   & nbsp;  $str = ' <div class= ' bd clearfix "id=" Index_hilite_ul "><ul class=" list "><li><div class=" cover "><a class=" text "href=" Http://www.jb51.net "> <strong>yuna</strong><p>love</p></a><strong class= "T g" >want to know</ Strong><a href= "/login.html" class= "ppbtn" ><strong "text" class= Div></li></ul></div> ';      $obj = new Htmlattributefilter ();      //Allow ID properties   $obj->setallow (array (' ID '));      $obj->setexception (Array (      ' a ' => array (' href '), //A label allows href attribute exceptions   &Nbsp;  ' ul ' => Array (' class ')//UL tag allows to have class attribute exceptions  ));     //IMG tag ignores, does not filter any properties   $OB J->setignore (Array (' img '));      echo ' source str:<br> ';  Echo htmlspecialchars ($ STR). ' <br><br> ';  echo ' filter str:<br> ';  echo htmlspecialchars ($obj->strip ($str));  ?>
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.