php 自带字符过滤,php strip_tags()如何只过滤字符串中某一个标签

本文介绍了如何在PHP中创建一个函数strip_only_tags(),用于移除字符串中指定的HTML标签,而非使用strip_tags()。该函数允许您保留或删除标签内的内容,并通过示例展示了如何使用它来过滤a、em、b等标签。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php去掉字符串中指定的html标签,我们不能使用strip_tags()函数,因为这个函数只能保留想要的html标签,如:

strip_tags($string); //去掉$string字符串中所以的html标签. http://www.manongjc.com/article/1213.html

strip_tags($string,'

'); //去掉除了
以外的所有标签,即保留字符串中的div、img、em标签。

要实现去掉指定的html标签,我们只能自己写一个函数,函数如下:

function strip_only_tags($str, $tags, $stripContent = FALSE) {

$content = '';

if (!is_array($tags)) {

$tags = (strpos($str, '>') !== false ? explode('>', str_replace('

if (end($tags) == '') {

// http://www.manongjc.com/article/1213.html

array_pop($tags);

}

}

foreach($tags as $tag) {

if ($stripContent) {

$content = '(.+|s[^>]*>)|)';

}

$str = preg_replace('#|s[^>]*>)'.$content.'#is', '', $str);

}

return $str;

}

参数介绍:

$str是指需要过滤的字符串。

$tags是指要移除的html标签。

$stripContent表示是否移除标签内的内容,默认为False,即不删除标签内的内容。

使用实例:

$string='

';

$target = strip_only_tags($string, array('a','em'));//移除$string字符串内的a、em、b标签。

var_dump($target);

$target = strip_only_tags($string, array('em'),true); //移除$string字符串内的a、em、b标签,并移除标签里面的内容

var_dump($target);

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值