php 过滤html标记属性类

2023-05-16

php 过滤html标记属性类


HtmlAttributeFilter.class.php

<?php
/** HTML Attribute Filter
*   Date:   2013-09-22
*   Author: fdipzone
*   ver:    1.0
*
*   Func:
*   public  strip              过滤属性
*   public  setAllow           设置允许的属性
*   public  setException       设置特例
*   public  setIgnore          设置忽略的标记
*   private findElements       搜寻需要处理的元素
*   private findAttributes     搜寻属性
*   private removeAttributes   移除属性
*   private isException        判断是否特例
*   private createAttributes   创建属性
*   private protect            特殊字符转义
*/

class HtmlAttributeFilter{ // class start

    private $_str = '';            // 源字符串
    private $_allow = array();     // 允许保留的属性 例如:array('id','class','title')
    private $_exception = array(); // 特例 例如:array('a'=>array('href','class'),'span'=>array('class'))
    private $_ignore = array();    // 忽略过滤的标记 例如:array('span','img')


    /** 处理HTML,过滤不保留的属性
    * @param  String $str 源字符串
    * @return String
    */
    public function strip($str){
        $this->_str = $str;

        if(is_string($this->_str) && strlen($this->_str)>0){ // 判断字符串

            $this->_str = strtolower($this->_str); // 转成小写

            $res = $this->findElements();
            if(is_string($res)){
                return $res;
            }
            $nodes = $this->findAttributes($res);
            $this->removeAttributes($nodes);
        }

        return $this->_str;
    }


    /** 设置允许的属性
    * @param Array $param
    */
    public function setAllow($param=array()){
        $this->_allow = $param;
    }


    /** 设置特例
    * @param Array $param
    */
    public function setException($param=array()){
        $this->_exception = $param;
    }


    /** 设置忽略的标记
    * @param Array $param
    */
    public function setIgnore($param=array()){
        $this->_ignore = $param;
    }


    /** 搜寻需要处理的元素 */
    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;
        }
    }


    /** 搜寻属性
    *  @param Array $nodes 需要处理的元素
    */
    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){
                    $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;
    }


    /** 移除属性
    *  @param Array $nodes 需要处理的元素
    */
    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']);
                    }
                }
            }
            $replacement = ($new_attributes) ? "<$node_name $new_attributes>" : "<$node_name>";
            $this->_str = preg_replace('/'.$this->protect($node['literal']).'/', $replacement, $this->_str);
        }
    }


    /** 判断是否特例
    * @param String $element_name   元素名
    * @param String $attribute_name 属性名
    * @param Array  $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[$element_name])){
                return true;
            }
        }
        return false;
    }


    /** 创建属性
    * @param  String $new_attributes
    * @param  String $name
    * @param  String $value
    * @return String
    */
    private function createAttributes($new_attributes, $name, $value){
        if($new_attributes){
            $new_attributes .= " ";
        }
        $new_attributes .= "$name=\"$value\"";
        return $new_attributes;
    }


    /** 特殊字符转义
    * @param  String $str 源字符串
    * @return String
    */
    private function protect($str){
        $conversions = array(
            "^" => "\^", 
            "[" => "\[", 
            "." => "\.", 
            "$" => "\$", 
            "{" => "\{", 
            "*" => "\*", 
            "(" => "\(", 
            "\\" => "\\\\", 
            "/" => "\/", 
            "+" => "\+", 
            ")" => "\)", 
            "|" => "\|", 
            "?" => "\?", 
            "<" => "\<", 
            ">" => "\>" 
        );
        return strtr($str, $conversions);
    }

} // class end

?>
demo
<?php
require('HtmlAttributeFilter.class.php');

$str = '<div class="bd clearfix" id="index_hilite_ul"><ul class="list"><li><img src="http://su.bdimg.com/static/skin/img/logo_white.png" width="118" height="148"><div class="cover"><a class="text" href="http://www.csdn.net"><strong>yuna</strong><p>love</p></a><strong class="t g">want to know</strong><a href="/login.html" class="ppBtn"><strong class="text">YES</strong></a></div></li></ul></div>';

$obj = new HtmlAttributeFilter();

// 允许id属性
$obj->setAllow(array('id'));

$obj->setException(array(
                    'a' => array('href'),   // a 标签允许有 href属性特例
                    'ul' => array('class')  // ul 标签允许有 class属性特例
));

// img 标签忽略,不过滤任何属性
$obj->setIgnore(array('img'));

echo 'source str:<br>';
echo htmlspecialchars($str).'<br><br>';
echo 'filter str:<br>';
echo htmlspecialchars($obj->strip($str));
?>


源文件下载:点击下载

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

php 过滤html标记属性类 的相关文章

  • ckeditor 字体样式 13 px

    我之前曾问过相关问题 但在尝试了所有发生错误的可能性之后 我发现 在ckeditor中 如果您复制一些文本并粘贴它 它默认粘贴为 p style font size 13px 示例图片 HTML CODE p div p Original
  • php exec 返回的结果比直接进入命令行要少

    我有一个 exec 命令 它的行为与通过 Penguinet 给 linux 的相同命令不同 res exec cd mnt mydirectory zcat log file gz echo res 当将命令直接放入命令行时 我在日志文件
  • filter_input() 何时删除 POST 变量的斜杠?

    我创建了一个小型 PHP 脚本 它在 PHP 5 2 17 的服务器上运行magic quotes gpc指令已启用 我没有对 php ini 文件的写访问权限 并且我想从用户输入中删除所有斜杠 即使magic quotes gpc指令被关
  • Ionic 2 占位符文本样式

    我正在使用 Ionic 2 rc0 开发一个应用程序 并且整个应用程序中有几个仍然需要样式设置的输入字段
  • 为整个网站设置单个图标

    目前我正在使用这段代码将网站图标添加到网站 但是 必须将此代码添加到每个 HTML 页面中 有谁知道如何设置全局图标 我看过的所有地方都告诉我必须将其添加到每个页面 UPDATE Chrome 在根目录中搜索 favicon ico 文件
  • Opencart 的 $this->config->get('module_var_name')

    我正在尝试自定义 Opencart 支付模块 我看到很多地方都使用了配置信息 但我找不到任何创建正在使用的变量的内容 我知道在管理页面中 如果我选择 paypal 标准 我可以设置所有 配置 信息 但我找不到强调它的 模型 是否有模型 我希
  • 无法显示由 Fine-uploader 上传到 Amazon s3 的图像

    我现在尝试设置fineuploader s3以显示在aws服务器上成功上传的文件的图像 如示例页面上所做的那样 http fineuploader com s3 demo http fineuploader com s3 demo 我 仍然
  • 使用php插入sql数据库时出错

    我有一个带有 MySQL 插入查询的程序 sql INSERT INTO people person id name username password email salt VALUES person id name username p
  • 如何使用php在mysql数据库中添加照片? [关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 我对 PH
  • Laravel 类邮件程序不存在

    我将应用程序从 5 更新到 5 2 现在 当我调用 Mail send 时 它会返回一个异常 Class mailer 不存在 Mail send emails mail data gt content function m use to
  • Laravel 上传前如何压缩图像?

    我正在制作一个图片库网站 用户可以在其中上传任何图像 它们将显示在前端 我需要在不影响图像质量的情况下压缩图像 以减小图像大小 以便页面加载速度不会影响那么大 我使用以下代码来上传图像 rules array file gt require
  • 扫描 PHP 上传的病毒

    我目前正在使用以下代码来扫描作为申请表的一部分上传的文件 safe path escapeshellarg dir file command usr bin clamscan stdout safe path out int 1 exec
  • 使用 IntlDateFormatter 转换非公历日期

    我应该如何使用将非公历日期转换为其他日历类型IntlDateFormatter 我要转换 1392 01 02 from persian to islamic日历 我尝试了以下代码 但它没有转换日历 formatter IntlDateFo
  • 为什么 jQuery 点击事件会多次触发

    我这里有这个示例代码http jsfiddle net DBBUL 10 http jsfiddle net DBBUL 10 document ready function creategene click function confir
  • 将一个文本框的内容复制到另一个文本框

    假设在文本框中输入了一个条目 是否可以在第二个文本框中保留相同的输入文本 如果是这样 这是如何完成的
  • 在 PHP 中使用数组来比较用户名/密码

    我有以下 php 脚本 其中有一个用户名和密码 Username user1 Password pass1 if isset POST submitform Clean up the input values foreach POST as
  • HTML colorpicker 发生变化时如何获取新值?

    我正在开发一个需要更改 HTML 颜色的网络应用程序canvas基于的价值观colorpicker 我有一个colorpicker在我需要获取的 HTML 中value从每次更新开始
  • 使用 html5 分块上传文件

    我正在尝试使用 html5 的文件 API 分块上传文件 然后在服务器端用 php 重新组装它 我正在上传视频 但是当我在服务器端合并文件时 大小增加了 并且它变成了无效文件 请注意 以下 html5 代码仅适用于 chrome 浏览器 在
  • PHP 中的简单 JSON 请求

    我有以下 json country code latitude 45 9390 longitude 24 9811 zoom 6 address city country Romania country code RO region 我只想
  • 使用“AND”表达式构建动态 SQL,而不混淆嵌套条件?

    总的来说 我对 php 和编码相当陌生 我有一系列条件需要测试它们是否已设置 它们是 option1 option2 option3 if isset option1 if isset option2 if isset option3 qu

随机推荐

  • libc++abi Specification

    void cxa allocate exception size t thrown size throw Effects Allocates memory to hold the exception to be thrown thrown
  • Java:利用递归方法求鸭子数

    问题描述 xff1a 一个人赶着鸭子去每个村庄卖 xff0c 每经过一个村子卖去所赶鸭子的一半又一只 这样他经过了七个村子后还剩两只鸭子 xff0c 问他出发时共赶多少只鸭子 xff1f 经过每个村子卖出多少只鸭子 xff1f 题目分析 x
  • 登录授权验证之OAuth2.0

    实际应用项目 xff1a http github crmeb net u long 本文将从几个方面了解和学习使用OAuth2 0 对不对就不管了 xff0c 反正我也几乎不会用到 ps 有个项目用到了 xff0c 所以才会有本文 OAut
  • PostgreSQL的视图以及物化视图的特点

    1 视图 PostgreSQL视图其实和mysql视图是一样的 xff0c 视图其实是个虚拟的表 xff0c 实际上是一个SQL拼接而成的虚拟表 xff08 假表 xff09 xff0c 可能是有一个表或者多个表 视图关联而成的复杂的SQL
  • 尚硅谷---Vue3同步笔记

    一 初识Vue3 Vue3带来了什么 xff1f 1 性能上的提升 xff1a 更快 占用内存更少 2 源码的升级 xff1a 使用Proxy代替defineProperty实现响应式 重写虚拟DOM的实现和Tree Shaking Tre
  • 移动mgv2000_JL代工_s905l2_MT7668_emmc_免拆卡刷固件包

    移动mgv2000 JL代工 s905l2 MT7668 emmc 免拆卡刷固件包 特点 xff1a 1 适用于卡刷 xff1b 2 开放原厂固件屏蔽的市场安装和u盘安装apk xff1b 3 修改dns xff0c 三网通用 xff1b
  • 魔百和CM311-1A_YST、(YM)_安卓9_S905L3A_默认开启ADB_纯净精简语音_完美线刷包

    魔百和CM311 1A YST YM 安卓9 S905L3A 默认开启ADB 纯净精简语音 完美线刷包 固件特点 xff1a 1 修改dns xff0c 三网通用 xff1b 2 开放原厂固件屏蔽的市场安装和u盘安装apk xff1b 3
  • C++11:变长模板的迭代与递归扩展

    迭代的运行效率始终强于递归 xff0c 递归始终比迭代方便开发 变长模板属于C 43 43 11中比较复杂的技术 xff0c 在此简单介绍下 include lt iostream gt using namespace std templa
  • 虚拟机Secure Boot安全启动

    概述 Secure Boot 作为 UEFI 的一个选项 xff0c 它可以被设置为开启或关闭 Secure Boot 所需要的公钥证书被保存在计算机的主板的 FLASH 里面 xff0c FLASH 里面保存着 PK xff0c KEK
  • 端口被占用的原因及解决办法

    运行软件或者项目的时候 xff0c 出现以下问题 xff1a panic blademaster listen tcp 0 0 0 0 8080 listen tcp 0 0 0 0 8080 bind An attempt was mad
  • Rust 学习,与 node.js 交互

    1 背景 近期 xff0c 参与了一个活动 xff1a 学 Rust xff0c 免费拿树莓派 主要内容为开发应用 xff0c 在 node js 中调用 Rust 函数 实际上我认为在很多地方都能用上 Rust xff0c 鉴于活动要求
  • Zeal--一款支持207个离线文档的浏览器

    小编作为一个全栈工程师 xff0c 每个语言都会一点 xff0c 在写前端和后端的时候 xff0c 时长会打开好几个开发文档 xff0c 比如java css html 等 xff0c 有没有打开一个软件 xff0c 就能打开所有的帮助文档
  • Linux之间图像界面的传输 ssh -X username@{remote ip}

    之前用windows平台连接Linux平台 xff0c 总是通过Xshell 43 Xming来传输Linux系统的界面 现在在linux系统平台下 xff0c 通过ssh连接另一个Linux系统 xff0c 如何将远程Linux的图形界面
  • 利用图片Etag判断用户

    原理 xff1a 不使用Javascript xff0c SESSION xff0c COOKIES xff0c FLASH 利用图片Etag识别用户 1 根据用户的 REMOTE ADDR 与 HTTP USER AGENT 生成唯一Et
  • 音视频基础知识---封装格式介绍

    音视频基础知识汇总 xff1a 音视频基础知识 协议相关RTSP RTMP HLS 音视频基础知识 封装格式 音视频基础知识 视频编码格式 音视频基础知识 音频编码格式 音视频基础知识 像素格式RGB 音视频基础知识 像素格式YUV 1 什
  • php output_buffering 缓存使用

    buffer是一个内存地址空间 xff0c linux系统默认大小一般为4096 4kb 主要用于存储速度不同步的设备或优先级不同的设备之间传递数据的区域 通过buffer可以使进程之间的相互等待变少 例如 xff0c 当你打开一个文本编辑
  • 同一域名对应不同IP,访问指定主机文件内容的方法

    PHP获取远程主机文件内容方法很多 xff0c 例如 xff1a file get contents xff0c fopen 等 lt php echo file get contents 39 http demo fdipzone com
  • php 实现BigPipe分块输出

    原理 xff1a 利用 ob flush 与 flush 将缓冲区的内容提前输出 xff0c 浏览器可提早加载这部分的内容 xff0c 无需等待所有输出完成再加载 将页面内容划分为一个个小块 xff0c 输出一个后再输出下一个 xff0c
  • php 利用fsockopen GET/POST 提交表单及上传文件

    php 利用 fsockopen GET POST 提交表单及上传文件 1 GET get php lt php host 61 39 demo fdipzone com 39 port 61 80 errno 61 39 39 errst
  • php 过滤html标记属性类

    php 过滤html标记属性类 HtmlAttributeFilter class php lt php HTML Attribute Filter Date 2013 09 22 Author fdipzone ver 1 0 Func