php RegExp: how to use newline in expression?

与世无争的帅哥 提交于 2019-12-11 02:49:09

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/7512781/php-regexp-how-to-use-newline-in-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!