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

时间:2011-09-22 09:46:28

标签: php regex preg-match preg-match-all modifier

例如它有效:

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

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

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

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

1 个答案:

答案 0 :(得分:4)

那将是/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