如何以比使用strip_tags函数更安全的方式剥离标签? [英] How to strip tags in a safer way than using strip_tags function?

查看:168
本文介绍了如何以比使用strip_tags函数更安全的方式剥离标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串包含小于和大于符号时,我使用strip_tags PHP函数有一些问题。例如:

I'm having some problems using strip_tags PHP function when the string contains 'less than' and 'greater than' signs. For example:

如果我这样做:

strip_tags("<span>some text <5ml and then >10ml some text </span>");

我会得到:

some text 10ml some text

但是,显然我想得到:

But, obviously I want to get:

some text <5ml and then >10ml some text

是的,我知道我可以使用& lt;和& gt,但是我没有机会将这些字符转换成HTML实体,因为数据已经存储在我的例子中,可以看到。

Yes I know that I could use &lt; and &gt;, but I don't have chance to convert those characters into HTML entities since data is already stored as you can see in my example.

因为TinyMCE被用于生成这些数据,所以我知道哪个实际的HTML标签是真正的HTML标签。

What I'm looking for is a clever way to parse HTML in order to get rid only actual HTML tags.

标签可以在任何情况下使用,所以一个 strip_tags($ string,$ black_list)实现将比 strip_tags($ string,$ allowed_tags

Since TinyMCE was used for generate that data, I know which actual html tags could be used in any case, so a strip_tags($string, $black_list) implementation would be more usefull than strip_tags($string, $allowable_tags).

任何事情?

推荐答案

p>作为一个古怪的解决方法,您可以使用以下方式过滤非html括号:

As a wacky workaround you could filter non-html brackets with:

$html = preg_replace("# <(?![/a-z]) | (?<=\s)>(?![a-z]) #exi", "htmlentities('$0')", $html);

之后应用strip_tags()。请注意,这仅适用于您的具体示例和类似情况。这是一个具有一些启发式的正则表达式,而不是人为的智能从其他意义的未转义的尖括号中识别html标签。

Apply strip_tags() afterwards. Note how this only works for your specific example and similar cases. It's a regular expression with some heuristics, not artificial intellegince to discern html tags from unescaped angle brackets with other meaning.

这篇关于如何以比使用strip_tags函数更安全的方式剥离标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆