Home > php教程 > php手册 > body text

php 去掉指定的html标签及内容

WBOY
Release: 2016-05-25 16:55:10
Original
1628 people have browsed it
本文章给家收集了大量的关于html标签的去除方法,很多朋友可能会想到使用strip_tags函数,但这个函数会把所有的html标签全部删除了,下面我来给大家介绍去掉指定的html标签及内容方法,有需要了解的朋友可参考。

string strip_tags ( string str [, string allowable_tags] )

弊端 :

这个函数只能保留想要的html标签,就是参数string allowable_tags。
在yizero的评论中我知道了这个函数的参数allowable_tags的其他的用法。

 代码如下 复制代码

strip_tags($source, ”); 去掉所以的html标签。

strip_tags($source, ‘

php 去掉指定的html标签及内容 ’); 保留字符串中的div、img、em标签。

如果想去掉的html的指定标签。那么这个函数就不能满足需求了。于是乎我用到了这个函数。

 

 代码如下 复制代码
/**
* 删除指定的HTML标签及其中内容,暂时只支持单标签清理
*
* @param string $string -- 要处理的字符串
* @param string $tagname -- 要删除的标签名称
* @param boolean $clear -- 是否删除标签内容
* @return string -- 返回处理完的字符串
*/
function replace_html_tag($string, $tagname, $clear = false){
$re = $clear ? '' : '1';
$sc = '/]*)?>([sS]*?)?' . $tagname . '>/i';
return preg_replace($sc, $re, $string);
}


以下是测试代码

 代码如下 复制代码

// 百度首页内容

$string = file_get_contents('http://www.phprm.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;
?>

如果我们要删除指定两者之间的数据

 

 代码如下 复制代码
/**  
* PHP去掉特定的html标签
* @param array $string  
* @param bool $str 
* @return string
*/ 
function _strip_tags($tagsArr,$str) {  
    foreach ($tagsArr as $tag) { 
        $p[]="/(]*>)/i"; 
    } 
    $return_str = preg_replace($p,"",$str); 
    return $return_str; 

 
$str = "您好百度一下,你就知道"; 
echo _strip_tags(array("b", "input", "a"),$str); #去掉 B 标签和 INPUT 标签 
?>



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!