【问题标题】:need explanation on a regular expression需要正则表达式的解释
【发布时间】:2013-03-23 12:34:05
【问题描述】:

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

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

有人在How to strip tags in a safer way than using strip_tags function? 上添加了它,但我无法理解。

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

谢谢!

【问题讨论】:

  • 粘贴完整的代码,最后的$html是什么?
  • strip_tags 是完全安全的。但是您必须将其与循环一起使用。如果有人可以正确使用正则表达式,他可以正确使用 strip_tags。但问题当然不是关于它的。
  • 当心,preg_replace 上的 e 修饰符是一个(可能的)安全漏洞(可能允许代码执行),将在 PHP 5.5 中弃用
  • @silentboy 是的.. 但我对 strip_tags 的感觉很糟糕,它会剥离 之间的所有文本,不管它是否是 html 标签
  • @CarlosCampderrós 谢谢卡洛斯 .. 我会进一步看

标签: php regex


【解决方案1】:
#...#      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

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

【讨论】:

    【解决方案2】:

    在我看来,它试图仅根据 之后的以下字符是否为数字来确定什么不是 HTML 标记。

    这意味着它将在此捕获&lt;

    &lt;span&gt;This is &lt;5 ml.&lt;/span&gt;

    并将其替换为与该字符等效的 HTML 实体,让您可以安全地使用 strip_tags 而不会破坏字符串的含义(如您引用的问题中所述)。

    【讨论】:

    • 感谢您的回答!是的,确实如此,但由于我不是正则表达式方面的专家,所以我想了解每个正则表达式构造的目的是什么。
    【解决方案3】:

    寻找&lt; 后面没有a-z

    空格后跟&gt;,后面不跟a-z

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

    i 选项忽略大小写

    e 进行正常替换

    x 忽略文字空格

    【讨论】:

    • 感谢您的解释。
    猜你喜欢
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多