如何以比使用strip_tags函数更安全的方式剥离标签?

tex*_*xai 7 php dom html-parsing strip-tags

当字符串包含'小于'和'大于'符号时,我在使用strip_tags PHP函数时遇到一些问题.例如:

如果我做:

strip_tags("<span>some text <5ml and then >10ml some text </span>");
Run Code Online (Sandbox Code Playgroud)

我去拿:

some text 10ml some text
Run Code Online (Sandbox Code Playgroud)

但是,显然我想得到:

some text <5ml and then >10ml some text
Run Code Online (Sandbox Code Playgroud)

是的我知道我可以使用< 和>,但我没有机会将这些字符转换为HTML实体,因为数据已经存储,如您在我的示例中所见.

我正在寻找的是一种解析HTML的聪明方法,以便只删除实际的HTML标签.

由于TinyMCE用于生成该数据,我知道在任何情况下都可以使用哪些实际的html标签,因此strip_tags($string, $black_list)实现将比实现更有用strip_tags($string, $allowable_tags).

有没有?

mar*_*rio 6

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

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

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