2013-08-26 89 views
0

我試圖從字符串中提取兩個字符串。字符串的格式如下:使用preg_match從字符串中提取兩個字符串

$text = 'First string here(second here)'; 

秒字符串將始終在引號內的末尾。我試圖有效地提取它們。我試過使用這個:preg_match('#\((.*?)\)#', $text, $match)preg_match('/\(([^\)]+)\)/', $text, $match)

上述表達式工作正常,但我試圖做到一口氣,不分開。我想這是我的強迫症在踢:/

回答

0

您可以使用捕捉組:

$text = 'First string here(second here)'; 
if (preg_match('#^([^\(]+)\(([^\)]+)\)$#', $text, $match)) { 
    print "$match[1]\n"; 
    print "$match[2]"; 
} 

See demo on ideone

0
$out= preg_split('/[\(\)]/',$text)[1]; 
+0

這是完美的,但我如何從秒字符串中刪除括號? – user962449

+0

@ user962449希望編輯幫助 – Anirudha

+0

次要的東西,但我會包括['PREG_SPLIT_NO_EMPTY'](http://php.net/manual/en/function.preg-split.php)標誌([示例](http: //ideone.com/2DvsiU))。 – Emissary