使用PHP的内部函数strip_tags可以很方便的删除掉字符串中的所有HTML标签,但是很多情况下我们只需要删除某个特定的标签,有没有什么简单的办法呢?我仔细查看了下PHP手册,其实有个例子已经实现了,很少有人注意到,我简单的介绍一下。
<?php
function strip_selected_tags($text, $tags = array())
{
$args = func_get_args();
$text = array_shift($args);
$tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags;
foreach ($tags as $tag){
if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
$text = str_replace($found[0],$found[1],$text);
}
} return $text;
}
?>
function strip_selected_tags($text, $tags = array())
{
$args = func_get_args();
$text = array_shift($args);
$tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags;
foreach ($tags as $tag){
if(preg_match_all('/<'.$tag.'[^>]*>(.*)<\/'.$tag.'>/iU', $text, $found)){
$text = str_replace($found[0],$found[1],$text);
}
} return $text;
}
?>
这个函数很短,但它实现的功能很实用,第一个参数是原字符串,第二个参数是要删除的HTML的标签数组,如果要删除<a>和<p>标签,只需要使用下面的代码:
<?php
$tags = array();
$tags[0]='a';
$tags[1]='p';
$str = "<a href=http://www.ajaxstu.com>link</a><p>help</p>";
echo strip_selected_tags($str,$tags);
?>
$tags = array();
$tags[0]='a';
$tags[1]='p';
$str = "<a href=http://www.ajaxstu.com>link</a><p>help</p>";
echo strip_selected_tags($str,$tags);
?>
是不是很简单呢?
