strip_tags() 函数我们一般用来剥离调用内容中的 html 标签,但在实际应用中我们可能会遇到这种情况,就是我们只想剥离大部分的html标签,还想保留某一个或几个html标签,不需要全部剥离掉。这时我们也是可以利用 strip_tags() 函数来实现的。
在 PHP 中使用 strip_tags() 函数保留多个 HTML 标签的方法,我们可以用第二个参数来设置不需要删除的标签,主要涉及到 strip_tags 函数的第二个参数。
strip_tags 函数
strip_tags 语法:
string strip_tags ( string str [, string allowable_tags] )
返回一个去除了 HTML 标签的字符串;可以使用第二个参数来设置不需要删除的标签。
使用 strip_tags 保留标签的方法:
前提:假如现在有这样一个字符串,
$doing = "
";1,不保留任何 HTML 标签,可以这样写代码:
echo strip_tags($doing);
// 输出:我来自
2,如果我们想保留 一个标签,可以将 字符串写到 strip_tags 的第二个参数中,代码这样写:
echo strip_tags($str, "");
3,而当我们想要保留
与…多个标签时,我们需要将多个标签用空格分隔后写到 strip_tags 的第二个参数中,代码这样写:
echo strip_tags($str, "
");
// 输出:
我来自
如果要使用 strip_tags() 函数来删除 html 标记中的特定标签又该如何操作呢?
这个可能就需要用以下代码来实现了,请看: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('/
'[^>]*>([^
'>/iu', $text, $found)){
$text = str_replace($found[0], $found[1], $text);
}
}
return preg_replace('/(
')( | |.)*/>)/iu', '', $text);
}$doing = "[url="] 123[/url]";
echo strip_selected_tags($doing, array('b'));