2013-12-12 66 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

相關問題