搜索
首页后端开发php教程php 过滤html标记属性类(附源码)

  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 过滤属性
  8. * public setAllow 设置允许的属性
  9. * public setException 设置特例
  10. * public setIgnore 设置忽略的标记
  11. * private findElements 搜寻需要处理的元素
  12. * private findAttributes 搜寻属性
  13. * private removeAttributes 移除属性
  14. * private isException 判断是否特例
  15. * private createAttributes 创建属性
  16. * private protect 特殊字符转义
  17. */
  18. class HtmlAttributeFilter{ // class start
  19. private $_str = ''; // 源字符串
  20. private $_allow = array(); // 允许保留的属性 例如:array('id','class','title')
  21. private $_exception = array(); // 特例 例如:array('a'=>array('href','class'),'span'=>array('class'))
  22. private $_ignore = array(); // 忽略过滤的标记 例如:array('span','img')
  23. /** 处理HTML,过滤不保留的属性
  24. * @param String $str 源字符串
  25. * @return String
  26. */
  27. public function strip($str){
  28. $this->_str = $str;
  29. if(is_string($this->_str) && strlen($this->_str)>0){ // 判断字符串
  30. $this->_str = strtolower($this->_str); // 转成小写
  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. /** 设置允许的属性
  41. * @param Array $param
  42. */
  43. public function setAllow($param=array()){
  44. $this->_allow = $param;
  45. }
  46. /** 设置特例
  47. * @param Array $param
  48. */
  49. public function setException($param=array()){
  50. $this->_exception = $param;
  51. }
  52. /** 设置忽略的标记
  53. * @param Array $param
  54. */
  55. public function setIgnore($param=array()){
  56. $this->_ignore = $param;
  57. }
  58. /** 搜寻需要处理的元素 */
  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. /** 搜寻属性
  79. * @param Array $nodes 需要处理的元素
  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. /** 移除属性
  100. * @param Array $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['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. /** 判断是否特例
  118. * @param String $element_name 元素名
  119. * @param String $attribute_name 属性名
  120. * @param Array $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. /** 创建属性

  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. /** 特殊字符转义
  145. * @param String $str 源字符串
  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,演示示例

  1. require('HtmlAttributeFilter.class.php');
  2. $str = '
    ';
  3. $obj = new HtmlAttributeFilter();
  4. // 允许id属性
  5. $obj->setAllow(array('id'));
  6. $obj->setException(array(
  7. 'a' => array('href'), // a 标签允许有 href属性特例
  8. 'ul' => array('class') // ul 标签允许有 class属性特例
  9. ));
  10. // img 标签忽略,不过滤任何属性
  11. $obj->setIgnore(array('img'));
  12. echo 'source str:
    ';
  13. echo htmlspecialchars($str).'

    ';
  14. echo 'filter str:
    ';
  15. echo htmlspecialchars($obj->strip($str));
  16. ?>
复制代码

附,php 过滤html标记属性类的源码下载地址



声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何防止与会议有关的跨站点脚本(XSS)攻击?您如何防止与会议有关的跨站点脚本(XSS)攻击?Apr 23, 2025 am 12:16 AM

要保护应用免受与会话相关的XSS攻击,需采取以下措施:1.设置HttpOnly和Secure标志保护会话cookie。2.对所有用户输入进行输出编码。3.实施内容安全策略(CSP)限制脚本来源。通过这些策略,可以有效防护会话相关的XSS攻击,确保用户数据安全。

您如何优化PHP会话性能?您如何优化PHP会话性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显着提升应用在高并发环境下的效率。

什么是session.gc_maxlifetime配置设置?什么是session.gc_maxlifetime配置设置?Apr 23, 2025 am 12:10 AM

thesession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceIsiseededeedeedeedeedeedeedto to to avoidperformance andununununununexpectedLogOgouts.3)

您如何在PHP中配置会话名?您如何在PHP中配置会话名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函数配置会话名称。具体步骤如下:1.使用session_name()函数设置会话名称,例如session_name("my_session")。2.在设置会话名称后,调用session_start()启动会话。配置会话名称可以避免多应用间的会话数据冲突,并增强安全性,但需注意会话名称的唯一性、安全性、长度和设置时机。

您应该多久再生一次会话ID?您应该多久再生一次会话ID?Apr 23, 2025 am 12:03 AM

会话ID应在登录时、敏感操作前和每30分钟定期重新生成。1.登录时重新生成会话ID可防会话固定攻击。2.敏感操作前重新生成提高安全性。3.定期重新生成降低长期利用风险,但需权衡用户体验。

如何在PHP中设置会话cookie参数?如何在PHP中设置会话cookie参数?Apr 22, 2025 pm 05:33 PM

在PHP中设置会话cookie参数可以通过session_set_cookie_params()函数实现。1)使用该函数设置参数,如过期时间、路径、域名、安全标志等;2)调用session_start()使参数生效;3)根据需求动态调整参数,如用户登录状态;4)注意设置secure和httponly标志以提升安全性。

在PHP中使用会议的主要目的是什么?在PHP中使用会议的主要目的是什么?Apr 22, 2025 pm 05:25 PM

在PHP中使用会话的主要目的是维护用户在不同页面之间的状态。1)会话通过session_start()函数启动,创建唯一会话ID并存储在用户cookie中。2)会话数据保存在服务器上,允许在不同请求间传递数据,如登录状态和购物车内容。

您如何在子域中分享会议?您如何在子域中分享会议?Apr 22, 2025 pm 05:21 PM

如何在子域名间共享会话?通过设置通用域名的会话cookie实现。1.在服务器端设置会话cookie的域为.example.com。2.选择合适的会话存储方式,如内存、数据库或分布式缓存。3.通过cookie传递会话ID,服务器根据ID检索和更新会话数据。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版