2012-06-24 166 views
2

我總是用preg_match,它總是能正常工作, 但今天我試圖讓兩個HTML標籤<code: 1>DATA</code>的preg_match返回空數組

之間的內容和我有一個問題,我的代碼解釋:

function findThis($data){ 
    preg_match_all("/\<code: (.*?)\>(.*?)\<\/code\>/i",$data,$conditions); 
    return $conditions; 
} 

    // plain text 
    // working fine 

    $data1='Some text...Some.. Te<code: 1>This is a php code</code>'; 

    //A text with a new lines 
    // Not working.. 

    $data2='some text.. 
    some.. te 
    <code: 1> 
    This is a php code 
    .. 
    </code> 
    '; 

    print_r(findThis($data1)); 

    // OUTPUT 
    // [0][0] => <code: 1>This is a php code</code> 
    // [1][0] => 1 
    // [2][0] => This is a php code 

    print_r(findThis($data2)); 

    //Outputs nothing! 
+0

的'*'佔位符不匹配換行,除非你指定'DOTALL修飾符'/ s'。 – mario

+1

可能的重複[如何匹配正則表達式中多行的任何字符?](http://stackoverflow.com/questions/159118/how-do-i-match-any-character-across-multiple-lines在一個正則表達式) – mario

回答

6

這是因爲。 PHP中的字符是的通配符,除了換行符。包括換行符的示例會中斷。你想要做的是將「s」標誌添加到你的模式的末尾,這會修改該模式。絕對匹配所有內容(包括換行符)。

/\<code: (.*?)\>(.*?)\<\/code\>/is 

在這裏看到:http://www.php.net/manual/en/regexp.reference.internal-options.php

+0

非常感謝你肖恩約翰遜,它現在工作正常..但另一個問題,如果我用一個非常長的文本這個函數,我會得到錯誤?有限制嗎?如果是這樣,我如何增加限制尺寸? –

+0

然而,限制是分配給PHP的內存。你必須處理一些非常大的數據才能達到這個極限。 –

+0

謝謝肖恩,終於十分鐘了,我能夠接受你的答案.. –