<?php
/**
* 删除指定的HTML标签及其中内容,暂时只支持单标签清理
*
* @param string $string -- 要处理的字符串
* @param string $tagname -- 要删除的标签名称
* @param boolean $clear -- 是否删除标签内容
* @return string -- 返回处理完的字符串
*/
function replace_html_tag($string, $tagname, $clear = false){
$re = $clear ? '' : '\1';
$sc = '/<' . $tagname . '(?:\s[^>]*)?>([\s\S]*?)?<\/' . $tagname . '>/i';
return preg_replace($sc, $re, $string);
}
/**
* 以下是测试代码
*/
// 百度首页内容
$string = file_get_contents('
http://www.baidu.com/');
// 去掉 style 及包含内容
$string = replace_html_tag($string, 'style', true);
$string = replace_html_tag($string, 'script', true);
// 去掉 a 标签,并保存其中内容
$string = replace_html_tag($string, 'a');
// 去掉 span 标签,并保存其中内容
$string = replace_html_tag($string, 'span');
echo $string;
?>