2013-12-12 65 views
4

我试图匹配跨越两行的一系列单词。PHP正则表达式与换行符不匹配换行

说我有以下文字:

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”修饰符来启用“。”。字符匹配新行,但我无法得到这个工作。有任何想法吗?

+1

这适用于我。也许你链接到的网站已损坏。 – MichaelRushton

+0

在您的测试页上,如果您单击preg_match_all的选项卡,则可以正确看到模式匹配。 – basicer

+0

是的,那个网站肯定是坏的。 'preg_match_all'和'preg_replace'工作正常,但'preg_match'将每行视为一个单独的输入。此外,底部的作弊表单从[Rubular](http://www.rubular.com/)逐字复制。 –

回答

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工作不正常,并给你错误的结果。

+0

感谢您确认它的正常工作。稍后我会在我的PHP环境中确认结果。 – http203

+1

它的工作原理。你是对的。测试网站有问题。 – http203

2

放入正则表达式的修改:

/(?s)test.*another/i 
+0

它似乎没有区别。 – http203

+0

当我测试它们时,这个和你使用的正则表达式工作得很好。正如@by255所指出的那样,你测试它的网站肯定有问题。事实上,如果您单击该站点右侧的“preg_replace”并填写替换值,您将看到该正则表达式实际上正常工作。 –

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 
+0

感谢您确认问题不在代码中。 – http203

+0

很高兴能帮到您 – hwnd

相关问题