php strip_tags()函数使用注意细节

来自:互联网
时间:2019-10-04
阅读:

php strip_tags()函数是去除字符串中的 HTML、XML 以及PHP的标签,返回去除标签之后的字符串,大家可以参考上一篇文章《PHP去掉HTML标签strip_tags()函数详解》,但在使用strip_tags()函数时,有几个细节要注意一下

strip_tags过滤后,内容丢失

使用php strip_tags()函数的时候,如果HTML标签不完整或者破损,将会导致更多的数据被删除,大家可以参考下面的例子

例:strip_tags()删除一段含有不完整HTML标签字符串

PHP代码

<?php
$name="<p>string</p>string-1<p><span hello </span></p><p>string-2</p>";
$tags=strip_tags($name,'<p>');
echo $tags;
?>

输入结果,如下图

strip_tags()函数使用注意

通过查看字符串可得知,字符中含有span标签出现错误,如下图

strip_tags()函数使用注意

我们修改一下代码再次运行,如下图,错误的位置的代码已修正

strip_tags()函数使用注意

修正后的代码:

<?php
//免费资源网
$name="<p>string</p>string-1<p><span> hello </span></p><p>string-2</p>";
$tags=strip_tags($name,'<p>');
echo $tags;
?>

运行结果:

strip_tags()函数过滤空格

strip_tags()不能过滤&nbsp;(空格)

strip_tags()函数,虽然可以过滤HTML标签,但对于&nbsp;(空格)不能过滤。比如下面的例子

strip_tags()函数过滤HTML空格

<?php
//免费资源网
$str = '哈哈哈&nbsp;&nbsp;&nbsp;免费资源网';
echo strip_tags($str);
?>

输出结果:

通过下图,可以清晰的查看到,输出到浏览器中的结果中,函数&nbsp(空格);

php strip_tags()函数使用注意细节

解决strip_tags()不能过滤&nbsp(空格);的方法

可以利用str_replace()函数先去掉&nbsp;,再过滤利用strip_tags()函数过滤HTML标签,很好的一个小技巧

修改代码如下:

<?php
//免费资源网
$str = '哈哈哈&nbsp;&nbsp;&nbsp;免费资源网';
echo strip_tags(str_replace('&nbsp;','',$str));
?>

输出结果如下图

php strip_tags()函数使用注意细节

返回顶部
顶部