2009-12-09 46 views
0
text text text 
text text text 

{test} 
    content 
    content 
    content 
{/test} 

text text text 
text text text 

我需要從上面的字符串兩個不同的結果:
1.PHP正則表達式匹配任何條件(包括空格)

{test} 
    content 
    content 
    content 
{/test} 

2.

content 
    content 
    content 

那麼,是什麼應該是兩個單獨的正則表達式PHP得到上面的兩種結果

+0

建議:放下你在做什麼,並學習如何使用正則表達式。他們會讓你在餘生過得很開心。 – 2009-12-09 05:45:03

+0

你可以通過一次調用preg_match();沒有必要使用兩個不同的正則表達式,這意味着要調用preg_match()兩次。 – kiamlaluno 2009-12-18 18:36:16

回答

3

什麼是這樣的:

$str = <<<STR 
text text text 
text text text 

{test} 
    content 
    content 
    content 
{/test} 

text text text 
text text text 
STR; 

$m = array(); 
if (preg_match('#\{([a-zA-Z]+)\}(.*?)\{/\1\}#ism', $str, $m)) { 
    var_dump($m); 
} 

這將讓這種輸出:

array 
    0 => string '{test} 
    content 
    content 
    content 
{/test}' (length=50) 
    1 => string 'test' (length=4) 
    2 => string ' 
    content 
    content 
    content 
' (length=37) 

所以,$m[0]你有整個匹配的字符串(即標籤+內容),並在$m[2]你只需要在標籤之間的內容。

注意我已經使用「通用」標籤,而不是專門用於「test」;如果您只有「test」標籤,則可以更改該標籤。

欲瞭解更多信息,你可以看看,至少:

+0

哦,對不起,我用[。*?]代替(。*?),那是我的錯!不過,謝謝你的回覆! 請你解釋一下詞條{/ \ 1} – 2009-12-09 05:48:48

+0

\ 1是匹配的第一個模式的「反向引用」。這裏的想法是結束標籤應該對應於開始標籤;;欲瞭解更多信息,你可以閱讀:http://www.php.net/manual/en/regexp.reference.back-references.php – 2009-12-09 05:49:58

1

要捕獲的標籤和內容一起:

/(\{test\}[^\x00]*?\{\/test\})/ 

爲了捕捉只是內容:

/\{test\}([^\x00]*?)\{\/test\}/