2011-12-18 32 views
0

我有一些文本字符串這樣PHP/Regex - 抓取{和}之間的所有內容?

{你好|喜} {存在|你}

我要計數的實例{..anything ..},所以這個例子以上,我希望回到:

招呼|喜
有|你

preg_match_all()創建的匹配陣列中

現在我的代碼如下所示:

preg_match_all('/{(.*?)}/', $text,$text_pieces); 

而且$ text_pieces包含:

Array ([0] => Array ([0] => {hello|hi} [1] => {there|you}) [1] => Array ([0] => hello|hi [1] => there|you)) 

所有我需要的是這樣的:

[0] => hello|hi [1] => there|you 

回答

2

preg_match_all不能忽略全文匹配,只有子模式匹配因此唯一的解決辦法是在函數調用後設置$text_pieces$text_pieces[1]

if(preg_match_all('/{(.*?)}/', $text,$text_pieces)) 
{ 
    $text_pieces = $text_pieces[1]; 
} 
+0

+!但是,您應該添加一些錯誤檢查代碼,以避免在沒有匹配時出現php運行時錯誤,例如當'preg_match_all()'返回0時。 – ridgerunner