search
HomeBackend DevelopmentPHP TutorialPHP filter html tag attribute class (source code attached)

  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 attribute
  8. * public setAllow set allowed Attributes
  9. * public setException Set special case
  10. * public setIgnore Set ignored mark
  11. * private findElements Search for elements that need to be processed
  12. * private findAttributes Search for attributes
  13. * private removeAttributes Remove attributes
  14. * private isException Determine whether it is a special case
  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(); // Allowed reserved attributes such as: array('id','class','title')
  21. private $_exception = array(); // Special cases such as: array('a'=>array ('href','class'),'span'=>array('class'))
  22. private $_ignore = array(); // Ignore filtered tags. For example: array('span','img')
  23. /**Process HTML, filter unretained attributes
  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){ // Determine the string
  30. $this->_str = strtolower($this->_str); // Convert 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 properties
  41. * @param Array $param
  42. */
  43. public function setAllow($param=array()){
  44. $this->_allow = $param;
  45. }
  46. /** Set special case
  47. * @param Array $param
  48. */
  49. public function setException($param=array()){
  50. $this->_exception = $param;
  51. }
  52. /**Set ignored tags
  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, 'attributes'=>$attributes);
  69. }
  70. }
  71. }
  72. if(!$nodes[0]){
  73. return $this->_str;
  74. }else{
  75. return $nodes;
  76. }
  77. }
  78. /**Search attribute
  79. * @param Array $nodes elements to be processed
  80. */
  81. private function findAttributes($nodes){
  82. foreach($nodes as &$node){
  83. preg_match_all("/( [^ =]+)s*=s*["|']{0,1}([^"']*)["|']{0,1}/i", $node['attributes'] , $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['attributes'] = null;
  93. }
  94. $node['attributes'] = $atts;
  95. unset($atts);
  96. }
  97. return $nodes;
  98. }
  99. /**Remove attributes
  100. * @param Array $nodes elements to be processed
  101. */
  102. private function removeAttributes($nodes){
  103. foreach($nodes as $node){
  104. $node_name = $node['name'];
  105. $new_attributes = '';
  106. if(is_array($node['attributes'])){
  107. foreach($node['attributes'] 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) ? "" : "";
  114. $this->_str = preg_replace('/'.$this->protect($node['literal']).'/', $replacement, $this->_str);
  115. }
  116. }
  117. /**Determine whether it is a special case
  118. * @param String $element_name element name
  119. * @param String $attribute_name attribute name
  120. * @param Array $exceptions allowed special cases
  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. /**创建属性

  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. /**Special character escape
  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. return strtr($str, $conversions);
  166. }
  167. } // class end
  168. ?>
复制代码

2, Demonstration example

  1. require('HtmlAttributeFilter.class.php');
  2. $str = '';
  3. $obj = new HtmlAttributeFilter();
  4. // Allow id attribute
  5. $ obj->setAllow(array('id'));
  6. $obj->setException(array(
  7. 'a' => array('href'), // a tag allows special cases of href attribute
  8. ' ul' => array('class') // The ul tag allows special cases of class attributes
  9. ));
  10. // The img tag 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. ?>
Copy the code

Attached, the source code download address of php filtering html tag attribute class



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools