2012-03-04 62 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);