2012-03-04 37 views
0

如何使用preg_match返回匹配(:)的所有子串的數組?如何使用preg_match來執行此操作?

舉例來說,如果我有一個字符串,它是:

My name is (:name), my dog's name is (:dogname) 

我想使用的preg_match返回

array("name", "dogname"); 

我用這個表達試...

preg_match("/\(:(?P<var>\w+)\)/", $string, $temp); 

但它只返回第一場比賽。

任何人都可以幫助我嗎?

+0

這就是['preg_match_all'](http://php.net/preg_match_all )是。注意'_all'後綴。 – mario 2012-03-04 00:45:12

+0

哦!難怪它沒有奏效。多麼尷尬...... – Rain 2012-03-04 00:55:06

回答

3

首先,你要preg_match_all(找到所有的結果),而不是preg_match(檢查是否有任何匹配的話)。

而對於實際的正則表達式時,最好的方法是尋找(:,然後搜索的任何字符,除了)

$string = "My name is (:name), my dog's name is (:dogname)"; 

$foundMatches = preg_match_all('/\(:([^)]+)\)/', $string, $matches); 
$matches = $foundMatches ? $matches[1] : array(); // get all matches for the 1st set of parenthesis. or if there were no matches, just an empty array 

var_dump($matches); 
+0

完美地工作,謝謝。 – Rain 2012-03-04 00:58:52

1

從文檔preg_match

preg_match()返回的時間模式相匹配的數量。這將是 0次(不匹配)或1次,因爲preg_match()將在第一次匹配後停止搜索 。 preg_match_all()相反將 繼續,直到它到達主題的末尾。 preg_match()返回 FALSE如果發生錯誤。

2

這會幫助你:)

$s = "My name is (:name), my dog's name is (:dogname)"; 
$preg = '/\(:(.*?)\)/'; 
echo '<pre>'; 
preg_match_all($preg, $s, $matches); 
var_dump($matches);