PHP Filter HTML tag attribute class Usage Example _php tips

Source: Internet
Author: User
Tags php class

This article describes the PHP filter HTML tag attribute class and its usage. is a more common practical skill in PHP project development. Share to everyone for your reference. The specific methods are as follows:

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

<?php/** HTML Attribute Filter * date:2013-09-22 * author:fdipzone * ver:1.0 * * Func: * Public stri  P Filter Properties * Public Setallow settings allowed properties * Public setexception Settings Exception * Public setignore settings ignored tags * private    Findelements search for elements to be processed * Private Findattributes search attribute * Private Removeattributes Remove attribute * Private isexception Judge whether special case * Private Createattributes Create attribute * Private protect Special word escape/class htmlattributefilter{/class Star      T private $_str = ';   SOURCE string Private $_allow = Array (); Properties that allow retention such as array (' ID ', ' class ', ' title ') Private $_exception = Array ();  Special cases such as: Array (' A ' =>array (' href ', ' class '), ' span ' =>array (' class ')) Private $_ignore = Array (); Ignore filtered tags For example: Array (' span ', ' img ')/** processing HTML, filtering attributes that are not preserved * @param string $str Source String * @return string/Pub 
 
    Lic function strip ($str) {$this->_str = $str; if (is_string ($this->_str) && strlen ($this->_str) >0) {//Judge characterstring $this->_str = Strtolower ($this->_str); 
      Convert to lowercase $res = $this->findelements (); 
      if (is_string ($res)) {return $res; 
      $nodes = $this->findattributes ($res); 
    $this->removeattributes ($nodes); 
  return $this->_str; /** set allowed properties * @param Array $param/Public Function Setallow ($param =array ()) {$this->_allow = $pa 
  Ram /** Set Special case * @param Array $param/Public Function setexception ($param =array ()) {$this->_exception 
  = $param; /** Set Ignored tags * @param Array $param/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 _ke 
    Y];    $element _name = $elements [1][$el _key]; 
        $attributes = $elements [2][$el _key]; if (Is_array ($this->_ignore) &&!in_array ($element _name, $this->_ignore)) {$nodes [] = Array (' Liter 
        Al ' => $literal, ' name ' => $element _name, ' attributes ' => $attributes); 
    }} if (! $nodes [0]) {return $this->_str; 
    }else{return $nodes; }/** Search Properties * @param Array $nodes elements to be handled */Private function findattributes ($nodes) {foreach ($node S 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 attributes * @param Array $nodes elements to be handled */Private function removeattributes ($nodes) {foreach ($nodes a 
      S $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->cre 
          Ateattributes ($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 a special case * @param string $element _name element name * @param string $attribute _name property name * @param Array $except 
    Ions Permitted 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->_exception[$ele 
      Ment_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 _attribut 
    Es. = ""; 
    $new _attributes. = "$name =\" $value \ ""; 
  return $new _attributes; /** Special Character Escape * @param string $str Source String * @return string/Private Function Protect ($STR) {$conver sions = Array ("^" => "\^", "[" => "\[", "." => "\.", "$" =&GT  "\$", "{" => "\{", "*" => "\*", "(" => "\", "\" => "\\\\", "/" => "\/", "+" => "\+", ")" => "\)", "|" => "\|", "?" => "\?", "<" =&gt ; 
    "\<", ">" => "\>"); 
  Return Strtr ($str, $conversions);

 }//Class end?>

The

Demo sample code is as follows:

<?php require (' HtmlAttributeFilter.class.php '); $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 attribute $obj->setallow (array (' ID ')); $obj->setexception (Array (' A ' => array (' href '),//A label allows the href attribute special case ' ul ' => Array (' class ')//UL tag allowed to have CLA 
 
SS attribute Special)); 
 
The IMG tag is ignored and does not filter any attributes $obj->setignore (Array (' IMG ')); 
echo ' Source str:<br> '; echo Htmlspecialchars ($str). ' 
<br><br> '; 
Echo ' Filter str:<br> '; 
Echo Htmlspecialchars ($obj->strip ($STR)); ?>

 

This article complete source code click here This machine downloads.

I hope this article will help you with your PHP program design.

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.