php過濾html標記屬性類用法例項

2022-09-27 09:30:14 字數 3074 閱讀 2259

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 i***ception 判斷是否特例

* private createattributes 建立屬性

* private protect 特殊字元轉義

*/

class htmlattributefilter

$nodes = $this->findattributes($res);

$this->removeattributes($nodes);

} return $this->_str;

} /** 設定允許的屬性

* @param array $param

*/ public function setallow($param=array())

/** 設定特例

* @param array $param

*/ public function setexception($param=array())

/** 設定忽略的標記

* @param array $param

*/ public function setignore($param=array())

/** 搜尋需要處理的元素 */

private function findelements()

} }

if(!$nodes[0])else

} /** 搜尋屬性

* @param array $nodes 需要處理的元素

*/ private function findattributes($nodes)([^\"']*)[\"|']/i", $node['attributes'], $attributes);

if($attributes[1])

}else

$node['attributes'] = $atts;

unset($atts);

} return $nodes;

} /** 移除屬性

* @param array $nodes 需要處理的元素

*/ private function removeattributes($nodes)

} }

$replacement = ($new_attributes) ? "" : "";

$this->_str = preg_replace('/'.$this->protect($node['literal']).'/', $replacement, $this->_str);

} }

/** 判斷是否特例

* @param string $element_name 元素名

* @param str程式設計客棧ing $attribute_name 屬性名

* @param arriydfpjzcay $exceptions 允許的特例

* @return boolean

*/ private function i***ception($element_name, $attribute_name, $exceptions)

} return false;

} /** 建立屬性

* @param string $new_attributes

* @param string $name

* @param string $value

* @return string

*/ private function createattributes($new_attributes, $name, $value)

$new_attributes .= "$name=\"$value\"";

return $new_attributes;

}

/** 特殊字元轉義

* @param string $str 源字串

* @return string

*/ private function protect($str)

} // class end

?>

demo示例**如下:

<?php require('htmlattributefilter.class.php');

$str = '

';

$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:

'; echo htmlspecialchars($str).'

'; echo 'filter str:

'; echo htmlspecialchars($obj->strip($str));

?>

php 過濾html標記屬性類

htmlattributefilter.class.php html attribute filter date 2013 09 22 author fdipzone ver 1.0 func public strip 過濾屬性 public setallow 設定允許的屬性 public sete...

php 過濾html標記屬性類

htmlattributefilter.class.php php view plain copy html attribute filter date 2013 09 22 author fdipzone ver 1.0 func public strip 過濾屬性 public setallow...

php過濾html標記屬性類用法例項

html attribute filter public strip 過濾屬性 public setallow 設定允許的屬性 public setexception 設定特例 public setignore 設定忽略的標記 private findelements 搜尋需要處理的元素 priva...