如何使用preg_match执行此操作?

时间:2012-03-04 00:43:23

标签: php regex

如何使用preg_match返回匹配(:)的所有子串的数组?

例如,如果我有一个字符串:

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

我想使用preg_match返回

array("name", "dogname");

我尝试使用这个表达式......

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

但它只返回第一场比赛。

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

这应该可以帮助你:)

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

答案 2 :(得分:1)

来自preg_match的文档:

  

preg_match()返回模式匹配的次数。那将是   0次(不匹配)或1次因为preg_match()将停止   在第一场比赛后搜索。 preg_match_all()恰恰相反   继续,直到它到达主题的结尾。 preg_match()返回   FALSE如果发生错误。

相关问题