搜尋
首頁後端開發php教程介紹php 過濾html標記屬性類別 的相關內容

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 = &#39;&#39;;            // 源字符串
    private $_allow = array();     // 允许保留的属性 例如:array(&#39;id&#39;,&#39;class&#39;,&#39;title&#39;)
    private $_exception = array(); // 特例 例如:array(&#39;a&#39;=>array(&#39;href&#39;,&#39;class&#39;),&#39;span&#39;=>array(&#39;class&#39;))
    private $_ignore = array();    // 忽略过滤的标记 例如:array(&#39;span&#39;,&#39;img&#39;)
    /** 处理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(&#39;literal&#39;=>$literal, &#39;name&#39;=>$element_name, &#39;attributes&#39;=>$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*[\"|&#39;]{0,1}([^\"&#39;]*)[\"|&#39;]{0,1}/i", $node[&#39;attributes&#39;], $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(&#39;literal&#39;=>$literal, &#39;name&#39;=>$attribute_name, &#39;value&#39;=>$value);
                }
            }else{
                $node[&#39;attributes&#39;] = null;
            }
            $node[&#39;attributes&#39;] = $atts;
            unset($atts);
        }
        return $nodes;
    }
    /** 移除属性
    *  @param Array $nodes 需要处理的元素
    */
    private function removeAttributes($nodes){
        foreach($nodes as $node){
            $node_name = $node[&#39;name&#39;];
            $new_attributes = &#39;&#39;;
            if(is_array($node[&#39;attributes&#39;])){
                foreach($node[&#39;attributes&#39;] as $attribute){
                    if((is_array($this->_allow) && in_array($attribute[&#39;name&#39;], $this->_allow)) || $this->isException($node_name, $attribute[&#39;name&#39;], $this->_exception)){
                        $new_attributes = $this->createAttributes($new_attributes, $attribute[&#39;name&#39;], $attribute[&#39;value&#39;]);
                    }
                }
            }
            $replacement = ($new_attributes) ? "<$node_name $new_attributes>" : "<$node_name>";
            $this->_str = preg_replace(&#39;/&#39;.$this->protect($node[&#39;literal&#39;]).&#39;/&#39;, $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(&#39;HtmlAttributeFilter.class.php&#39;);
$str = &#39;<p class="bd clearfix" id="index_hilite_ul"><ul class="list"><li><img  src="/static/imghwm/default1.png"  data-src="http://su.bdimg.com/static/skin/img/logo_white.png"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="介紹php 過濾html標記屬性類別 的相關內容" ><p 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></p></li></ul></p>&#39;;
$obj = new HtmlAttributeFilter();
// 允许id属性
$obj->setAllow(array(&#39;id&#39;));
$obj->setException(array(
                    &#39;a&#39; => array(&#39;href&#39;),   // a 标签允许有 href属性特例
                    &#39;ul&#39; => array(&#39;class&#39;)  // ul 标签允许有 class属性特例
));
// img 标签忽略,不过滤任何属性
$obj->setIgnore(array(&#39;img&#39;));
echo &#39;source str:<br>&#39;;
echo htmlspecialchars($str).&#39;<br><br>&#39;;
echo &#39;filter str:<br>&#39;;
echo htmlspecialchars($obj->strip($str));
?>

本篇讲解了介绍php 过滤html标记属性类 的相关内容,更多相关内容请关注php中文网。

相关推荐:

关于mysql 优化 insert 性能 的相关介绍

如何使用php 常用自定义方法

如何通过php 使用异或(XOR)加密/解密文件

以上是介紹php 過濾html標記屬性類別 的相關內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP如何識別用戶的會話?PHP如何識別用戶的會話?May 01, 2025 am 12:23 AM

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

確保PHP會議的一些最佳實踐是什麼?確保PHP會議的一些最佳實踐是什麼?May 01, 2025 am 12:22 AM

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

PHP會話文件默認存儲在哪裡?PHP會話文件默認存儲在哪裡?May 01, 2025 am 12:15 AM

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

您如何從PHP會話中檢索數據?您如何從PHP會話中檢索數據?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

您如何使用會議來實施購物車?您如何使用會議來實施購物車?May 01, 2025 am 12:10 AM

利用會話構建高效購物車系統的步驟包括:1)理解會話的定義與作用,會話是服務器端的存儲機制,用於跨請求維護用戶狀態;2)實現基本的會話管理,如添加商品到購物車;3)擴展到高級用法,支持商品數量管理和刪除;4)優化性能和安全性,通過持久化會話數據和使用安全的會話標識符。

您如何在PHP中創建和使用接口?您如何在PHP中創建和使用接口?Apr 30, 2025 pm 03:40 PM

本文解釋瞭如何創建,實施和使用PHP中的接口,重點關注其對代碼組織和可維護性的好處。

crypt()和password_hash()有什麼區別?crypt()和password_hash()有什麼區別?Apr 30, 2025 pm 03:39 PM

本文討論了PHP中的crypt()和password_hash()的差異,以進行密碼哈希,重點介紹其實施,安全性和對現代Web應用程序的適用性。

如何防止PHP中的跨站點腳本(XSS)?如何防止PHP中的跨站點腳本(XSS)?Apr 30, 2025 pm 03:38 PM

文章討論了通過輸入驗證,輸出編碼以及使用OWASP ESAPI和HTML淨化器之類的工具來防止PHP中的跨站點腳本(XSS)。

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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境