Php filters html tag attributes (with source code)

Source: Internet
Author: User
Php filters html tag attributes (with source code)

  1. /** HTML Attribute Filter

  2. * Date: 2013-09-22
  3. * Author: fdipzone
  4. * Ver: 1.0
  5. * Edit: bbs.it-home.org
  6. * Func:
  7. * Public strip filter attributes
  8. * Public setAllow: Set the allowed attributes.
  9. * Special case for setting public setException
  10. * Public setIgnore: Set the ignored flag.
  11. * Private findElements: Search for elements to be processed
  12. * Private findAttributes search attributes
  13. * Private removeAttributes: remove attributes
  14. * Private isException: determines whether a special case exists.
  15. * Private createAttributes: create attributes
  16. * Private protect special character escape
  17. */
  18. Class HtmlAttributeFilter {// class start
  19. Private $ _ str = ''; // source string
  20. Private $ _ allow = array (); // attributes that can be retained, for example, array ('id', 'class', 'title ')
  21. Private $ _ exception = array (); // special example: array ('a' => array ('href ', 'class '), 'span '=> array ('class '))
  22. Private $ _ ignore = array (); // ignore filtered tags, for example, array ('span ', 'IMG ')
  23. /** Process HTML and filter attributes that are not retained
  24. * @ Param String $ str Source String
  25. * @ Return String
  26. */
  27. Public function strip ($ str ){
  28. $ This-> _ str = $ str;
  29. If (is_string ($ this-> _ str) & strlen ($ this-> _ str)> 0) {// judge a string
  30. $ This-> _ str = strtolower ($ this-> _ str); // Convert it to lowercase.
  31. $ Res = $ this-> findElements ();
  32. If (is_string ($ res )){
  33. Return $ res;
  34. }
  35. $ Nodes = $ this-> findAttributes ($ res );
  36. $ This-> removeAttributes ($ nodes );
  37. }
  38. Return $ this-> _ str;
  39. }
  40. /** Set allowed attributes
  41. * @ Param Array $ param
  42. */
  43. Public function setAllow ($ param = array ()){
  44. $ This-> _ allow = $ param;
  45. }
  46. /** Set special cases
  47. * @ Param Array $ param
  48. */
  49. Public function setException ($ param = array ()){
  50. $ This-> _ exception = $ param;
  51. }
  52. /** Set the ignored flag
  53. * @ Param Array $ param
  54. */
  55. Public function setIgnore ($ param = array ()){
  56. $ This-> _ ignore = $ param;
  57. }
  58. /** Search for elements to be processed */
  59. Private function findElements (){
  60. $ Nodes = array ();
  61. Preg_match_all ("/<([^! \/\> \ N] +) ([^>] *)>/I ", $ this-> _ str, $ elements );
  62. Foreach ($ elements [1] as $ el_key => $ element ){
  63. If ($ elements [2] [$ el_key]) {
  64. $ Literal = $ elements [0] [$ el_key];
  65. $ Element_name = $ elements [1] [$ el_key];
  66. $ Attributes = $ elements [2] [$ el_key];
  67. If (is_array ($ this-> _ ignore )&&! In_array ($ element_name, $ this-> _ ignore )){
  68. $ Nodes [] = array ('literal' => $ literal, 'name' => $ element_name, 'bubuckets' => $ attributes );
  69. }
  70. }
  71. }
  72. If (! $ Nodes [0]) {
  73. Return $ this-> _ str;
  74. } Else {
  75. Return $ nodes;
  76. }
  77. }
  78. /** Search for attributes
  79. * @ Param Array $ elements to be processed by nodes
  80. */
  81. Private function findAttributes ($ nodes ){
  82. Foreach ($ nodes as & $ node ){
  83. Preg_match_all ("/([^ =] +) \ s * = \ s * [\" | '] {0, 1} ([^ \ "'] *) [\ "| '] {0, 1}/I", $ node ['bubuckets'], $ attributes );
  84. If ($ attributes [1]) {
  85. Foreach ($ attributes [1] as $ att_key => $ att ){
  86. $ Literal = $ attributes [0] [$ att_key];
  87. $ Attribute_name = $ attributes [1] [$ att_key];
  88. $ Value = $ attributes [2] [$ att_key];
  89. $ Atts [] = array ('literal' => $ literal, 'name' => $ attribute_name, 'value' => $ value );
  90. }
  91. } Else {
  92. $ Node ['bubuckets'] = null;
  93. }
  94. $ Node ['bubuckets'] = $ atts;
  95. Unset ($ atts );
  96. }
  97. Return $ nodes;
  98. }
  99. /** Remove attributes
  100. * @ Param Array $ elements to be processed by nodes
  101. */
  102. Private function removeAttributes ($ nodes ){
  103. Foreach ($ nodes as $ node ){
  104. $ Node_name = $ node ['name'];
  105. $ New_attributes = '';
  106. If (is_array ($ node ['bubuckets']) {
  107. Foreach ($ node ['buckets'] as $ attribute ){
  108. If (is_array ($ this-> _ allow) & in_array ($ attribute ['name'], $ this-> _ allow )) | $ this-> isException ($ node_name, $ attribute ['name'], $ this-> _ exception )){
  109. $ New_attributes = $ this-> createAttributes ($ new_attributes, $ attribute ['name'], $ attribute ['value']);
  110. }
  111. }
  112. }
  113. $ Replacement = ($ new_attributes )? "<$ Node_name $ new_attributes>": "<$ node_name> ";
  114. $ This-> _ str = preg_replace ('/'. $ this-> protect ($ node ['literal']). '/', $ replacement, $ this-> _ str );
  115. }
  116. }
  117. /** Determine whether a special case exists
  118. * @ Param String $ element_name element name
  119. * @ Param String $ attribute_name attribute name
  120. * @ Param Array $ special exceptions
  121. * @ Return boolean
  122. */
  123. Private function isException ($ element_name, $ attribute_name, $ exceptions ){
  124. If (array_key_exists ($ element_name, $ this-> _ exception )){
  125. If (in_array ($ attribute_name, $ this-> _ exception [$ element_name]) {
  126. Return true;
  127. }
  128. }
  129. Return false;
  130. }

  131. /** Create attributes

  132. * @ Param String $ new_attributes
  133. * @ Param String $ name
  134. * @ Param String $ value
  135. * @ Return String
  136. */
  137. Private function createAttributes ($ new_attributes, $ name, $ value ){
  138. If ($ new_attributes ){
  139. $ New_attributes. = "";
  140. }
  141. $ New_attributes. = "$ name = \" $ value \"";
  142. Return $ new_attributes;
  143. }
  144. /** Escape special characters
  145. * @ Param String $ str Source String
  146. * @ Return String
  147. */
  148. Private function protect ($ str ){
  149. $ Conversions = array (
  150. "^" => "\ ^ ",
  151. "[" => "\[",
  152. "." => "\.",
  153. "$" => "\ $ ",
  154. "{" => "\{",
  155. "*" => "\*",
  156. "(" => "\(",
  157. "\\" => "\\\\",
  158. "/" => "\/",
  159. "+" => "\ + ",
  160. ")" => "\)",
  161. "|" => "\ | ",
  162. "? "=> "\? ",
  163. "<" => "\ <",
  164. ">" => "\>"
  165. );
  166. Return strtr ($ str, $ conversions );
  167. }
  168. } // Class end
  169. ?>

2. Demo

  1. Require ('htmlattributefilter. class. php ');
  2. $ Str ='

    • Yuna

      Love

      Want to knowYES

    ';
  3. $ Obj = new HtmlAttributeFilter ();
  4. // Allow the id attribute
  5. $ Obj-> setAllow (array ('id '));
  6. $ Obj-> setException (array (
  7. 'A' => array ('href '), // a tag allows special cases with the href attribute
  8. 'Ul '=> array ('class') // The ul tag allows special class attribute exceptions.
  9. ));
  10. // The img label is ignored and no attributes are filtered.
  11. $ Obj-> setIgnore (array ('IMG '));
  12. Echo 'source str:
    ';
  13. Echo htmlspecialchars ($ str ).'

    ';
  14. Echo 'filter str:
    ';
  15. Echo htmlspecialchars ($ obj-> strip ($ str ));
  16. ?>

Appendix: php source code used to filter html tag attribute classes

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.