您的位置:首页 > 编程语言 > PHP开发

黄聪: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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: