Kob*_*obi 49
默认情况下.不匹配新行 - [\s\S]是解决该问题的方法.
这在JavaScript中很常见,但在PHP中,您可以使用/s标志来使点匹配所有字符.
cod*_*ict 19
的.元字符匹配除换行符之外的任何字符.因此,.*如果您必须匹配换行符,则用于匹配任何内容的模式将不起作用.
preg_match('/^.*$/',"hello\nworld"); // returns 0
Run Code Online (Sandbox Code Playgroud)
[\s\S]这是一个空白字符的字符类,非空白字符匹配任何字符,包括换行符,所以[\d\D],[\w\W].所以你的模式[\s\S]*现在匹配任何东西
preg_match('/^[\s\S]$/s',"hello\nworld"); // returns 1
Run Code Online (Sandbox Code Playgroud)
使.匹配任何东西(包括换行符)的替代方法是使用s修饰符.
preg_match('/^.*$/s',"hello\nworld"); // returns 1
Run Code Online (Sandbox Code Playgroud)
使用s修饰符的替代方法是将其包含在内:
preg_match('/^(?s).*(?-s)$/',"hello\nworld"); // returns 1
Run Code Online (Sandbox Code Playgroud)
(?s)打开s模式,(?-s)如果关闭则关闭.关闭后,任何后续内容.都不会与换行符匹配.