PHP 去除字符串中指定字符之间的字符

来源:百度知道 编辑:UC知道 时间:2024/05/31 13:54:59
我截取的网页,我想去掉代码中的CSS代码
CSS代码一般包含在HTML标记<style></style>中
用什么函数能去掉这两个标记之间的字符呢?
多谢!

<?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');