php 函数 strip_tags 提供了从字符串中去除 html 和 php 标记的功能,该函数尝试返回给定的字符串 str 去除空字符、html 和 php 标记后的结果。
由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数据被删除。
比如下述代码:
<div>string</div>string<strong><span style="COLOR: #ff0000"><</span></strong>string<b>hello</b><div>string</div>
通过 strip_tags($str, ‘
<div>string</div>string<strong><span style="COLOR: #ff0000"><</span></strong>stringhello<div>string</div>
而实际操作结果是这样的:
立即学习“PHP免费学习笔记(深入)”;
<div>string</div>string
这一切都是因为加红的那个左尖括号,查了 PHP 的文档,有一个警告提示:
由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数据被删除。
既然在执行过滤前无法验证代码正确性,遇到和标签相关的字符 “” 后面的代码就全挂了!
2013.01.11 更新:
以下方法可以解决该问题,但可能在 HTML 数据过大时,存在一定的效率问题,慎用!
function fixtags ($text) {
$text = htmlspecialchars($text);
$text = preg_replace("/"/", """", $text);
$tags = "/<(!|)(/|)(w*)( |)(w*)([\=]*)(?|(")"""|)(?|(.*)?"(")|)([ ]?)(/|)>/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10$11>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=""/", "=", $text);
$text = preg_replace("/""/", """, $text);
return $text;
}
使用方法:
strip_tags(fixtags($string), '<div>');
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号