需要解释正则表达式


need explanation on a regular expression

谁能给我解释一下这个正则表达式的含义?

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

有人在如何以比使用strip_tags功能更安全的方式剥离标签?但我不能理解。

这是我在stackoverflow上的第一篇文章,如果我犯了什么错误,请原谅我。

谢谢!

#...#      the # and # are just characters to start en end a REGEX
           (you can use a lot of character for this)
#exi       the e, x and i flags. See the PHP.net site for information
           about it
<          the < character
(?!...)    a negative lookahead. The REGEX matches when the characters
           after this are NOT equal to one of those
[/a-z]     a character class, matches for the / character and the
           letters a - z
|          OR
(?<='s)    a positive lookbehind. The REGEX maches when there is
           's (whitepspace) before
>          the > character
(?![a-z])  negative lookahead for the letters a - z

基本上,它匹配所有不用作标记的<>字符。例如,<foo</foo不匹配,foo>也不匹配。但1 < 3会匹配。这将被传递给htmlentities函数并成为1 &lt; 3。现在,您可以使用strip_tags仅删除标记。

在我看来,它试图确定什么不是HTML标签,仅仅基于是否在<或者>是一个数字。

这意味着它将捕获以下<:

<span>This is <5 ml.</span>

并将其替换为该字符的HTML实体等效,允许您安全地使用strip_tags而不会破坏字符串的含义(如参考问题中所讨论的)。

查找没有后跟a-z<

空格后跟>,不能后跟a-z

然后将其替换为htmlentities('$0'),其中$0是您的整个匹配!

i选项忽略大小写

e进行正常替换

x忽略空白文字