PHP正则表达式与换行符与s修饰符不匹配

时间:2013-12-12 17:43:26

标签: php regex

我正在尝试匹配跨越两行的一系列单词。

说我有以下文字:

this is a test
another line

我的正则表达式模式使用preg_match:

/test.*another/si

在这里测试: http://www.phpliveregex.com/p/2zj

PHP模式修饰符: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

我读过的所有内容都指向使用“s”修饰符启用“。”字符匹配新行,但我不能让这个工作。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

您的正则表达式是正确的,并且在我的本地计算机上正常运行:

$input_line = "this is a test
another line";

preg_match("/test.*another/si", $input_line, $output_array);
var_dump($output_array);

它产生以下输出:

array(1) {
  [0]=>
  string(13) "test
another"
}

所以我的猜测是phpliveregex.com工作不正常并给你错误的结果。

答案 1 :(得分:2)

将修饰符放在正则表达式中:

/(?s)test.*another/i

答案 2 :(得分:2)

s修饰符也称为dotall修饰符,强制点.也匹配换行符。

您的正则表达式使用正确,这似乎对我有用。

$text = <<<DATA
this is a test
another line
DATA;

preg_match('/test.*another/si', $text, $match);
echo $match[0];

请在此处查看demo

输出

test
another