发布时间:2014-08-31 23:41:23
来源:http://www.yourcode.org
作者:Yourcode
点击:632次
本文章给家收集了大量的关于html标签的去除方法,很多朋友可能会想到使用strip_tags函数,但这个函数会把所有的html标签全部删除了,下面我来给大家介绍去掉指定的html标签及内容方法,有需
本文章给家收集了大量的关于html标签的去除方法,很多朋友可能会想到使用strip_tags函数,但这个函数会把所有的html标签全部删除了,下面我来给大家介绍去掉指定的html标签及内容方法,有需要了解的朋友可参考。
string strip_tags ( string str [, string allowable_tags] )
弊端 :
这个函数只能保留想要的html标签,就是参数string allowable_tags。
在yizero的评论中我知道了这个函数的参数allowable_tags的其他的用法。
1
2
|
strip_tags
(
$source
,
''
);
//去掉所以的html标签。
strip_tags
(
$source
,
'<div><img><em>'
);
//保留字符串中的div、img、em标签。
|
如果想去掉的html的指定标签。那么这个函数就不能满足需求了。于是乎我用到了这个函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/**
* 删除指定的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[^>]*)?>([sS]*?)?</'
.
$tagname
.
'>/i'
;
return
preg_replace(
$sc
,
$re
,
$string
);
}
|
以下是测试代码
1
2
3
4
5
6
7
8
9
10
|
// 百度首页内容
$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
;
|
如果我们要删除指定两者之间的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php
/**
* PHP去掉特定的html标签
* @param array $string
* @param bool $str
* @return string
*/
function
_strip_tags(
$tagsArr
,
$str
) {
foreach
(
$tagsArr
as
$tag
) {
$p
[]=
"/(<(?:/"
.
$tag
.
"|"
.
$tag
.
")[^>]*>)/i"
;
}
$return_str
= preg_replace(
$p
,
""
,
$str
);
return
$return_str
;
}
$str
=
"<b>您好</b><input type='text' name='' /><a href='http://www.baidu.com'>百度一下,你就知道</a>"
;
echo
_strip_tags(
array
(
"b"
,
"input"
,
"a"
),
$str
); #去掉 B 标签和 INPUT 标签
?>
|