黄聪:PHP使用Simple_HTML_DOM遍历、过滤及保留指定属性
2015-12-25 17:32
302 查看
<? /* * 参考资料: * http://www.phpddt.com/manual/simplehtmldom_1_5/manual_api.htm * http://www.phpddt.com/manual/simplehtmldom_1_5/manual.htm */ class HtmlUtil{ /* * $allow:只允许这些属性存在 * $exceptions:一些特殊的元素,可以存在某些属性 */ public function clear_child_html_attribute( $html_dom, $allow = array(), $exceptions = array() ) { foreach( $html_dom->find('*') as $html_child_dom ) { $this->clear_child_html_attribute( $html_child_dom, $allow, $exceptions ); $this->clear_attribute( $html_child_dom, $allow, $exceptions ); } } public function clear_attribute( $html_dom, $allow = array(), $exceptions = array() ) { //遍历属性 $attrs = $html_dom->getAllAttributes(); if( count( $attrs ) > 0 ) { //遍历属性,进行处理 foreach( $attrs as $attr_key => $attr_value ) { //如果是例外的,则不管 $exceptions_attrs = $exceptions[ $html_dom->tag ]; if( is_array( $exceptions_attrs ) && in_array( $attr_key , $exceptions_attrs ) ){ continue; } //如果不再允许列表中,则删除 if( is_array( $allow ) && in_array( $attr_key , $allow ) ){ continue; } $html_dom->removeAttribute( $attr_key ); } } } public function clear_html_attribute( $html_str, $allow = array(), $exceptions= array() ) { include TEMPLATEPATH . '/class/simple_html_dom.php'; $html = str_get_html( $html_str ); foreach( $html->find( "*" ) as $html_dom ) { //处理所有节点的属性 $this->clear_child_html_attribute( $html_dom, $allow, $exceptions ); } return $html; } function clear_html_post( $post_id ) { if ( ! wp_is_post_revision( $post_id ) ){ remove_action('save_post', array( $this, 'clear_html_post') ); $my_post = get_post( $post_id ); $my_post->post_content = $this->clear_html( $my_post->post_content ); wp_update_post( $my_post ); add_action('save_post', array( $this, 'clear_html_post') ); } } } ?>
使用方法:
<? $html = "<p><a href='http://hcsem.com' style='color:#F00;' class='ttt'>黄聪的笔记本</a>还是<b class='test'>很不错</b>的哦!</p>"; $allow = array( 'style', 'colspan', 'rowspan', ); $exceptions = array( 'img' => array( 'src', 'alt' , 'title' , 'width' , 'height' , 'class', 'id' ), 'a' => array( 'href', 'title', 'target'), 'iframe'=>array('src','frameborder'), ); global $HtmlUtil; $HtmlUtil = new HtmlUtil; $html = $HtmlUtil->clear_html_attribute( $html, $allow, $exceptions ); //输出<p><a href='http://hcsem.com' style='color:#F00;'>黄聪的笔记本</a>还是<b>很不错</b>的哦!</p>
相关文章推荐
- Laravel中的日志与上传
- php【基础学习八】URL编解码
- php【基础学习七】string操作
- MSTP+VRRP组合实现S1和S2的(双交换)热备冗余及负载均衡
- php中图像处理
- PHP获取二维数组中某一列的值集合
- phpmyadmin安装教程及配置设置
- PHP版本升级到7.x后wordpress的一些修改及wordpress技巧
- webservice soap php接口
- ffmpeg安装使用及ffmpeg-php安装
- php curl_init函数用法
- Yii2 集成ueditor脚手架
- thinkphp 二级域名站点 session共享(单点登录)
- 全球可用的NTP服务器列表与解析服务
- PHP实现远程下载文件到本地
- PHP开启curl_init
- PHP、Java、C#实现URI参数签名算法,确保应用与REST服务器之间的安全通信,防止Secret Key盗用、数据篡改等恶意攻击行为
- PHP resource类型的实质是什么
- php浮点数精确运算
- Relearning PHP (2) – php 的浮点数float