php RegExp:如何在表达式中使用换行符?

发布于 2024-12-06 02:23:25 字数 401 浏览 1 评论 0原文

例如它的工作原理:

{<div\s+class=\"article\"><h2(.*)</div>}s

如果我这样做,我什么也得不到:

{<div\s+class=\"article\">
    <h2(.*)
 </div>}s

我怀疑我应该使用一些修饰符,但我知道这里是哪一个: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

For example it works:

{<div\s+class=\"article\"><h2(.*)</div>}s

If I do this way, I get nothing:

{<div\s+class=\"article\">
    <h2(.*)
 </div>}s

I suspect that I should use some modifier, but I know which one from here: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2024-12-13 02:23:25

这就是 /x 修饰符:

x (PCRE_EXTENDED)

<块引用>

如果设置了此修饰符,则模式中的空白数据字符将被完全忽略,除非转义或位于字符类内部,并且字符类外部未转义的 # 和下一个换行符之间的字符(包括在内)也将被忽略。这相当于 Perl 的 /x 修饰符,并且可以在复杂的模式中包含注释。但请注意,这仅适用于数据字符。空白字符可能永远不会出现在模式中的特殊字符序列中,例如在序列 (?( 中,它引入了条件子模式。

它还允许对模式进行注释,这非常有用:

{<div\s+class=\"article\">  # many spaces between the div and the attribute
    <h2(.*)                 # don't really care about closing the tag
 </div>}sx

That would be the /x modifier:

x (PCRE_EXTENDED)

If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.

It also allows commenting the pattern, which is extremely useful:

{<div\s+class=\"article\">  # many spaces between the div and the attribute
    <h2(.*)                 # don't really care about closing the tag
 </div>}sx
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文