php preg_match_all未获得所有结果

时间:2016-11-29 12:46:27

标签: php regex preg-match-all

我正在使用php preg_match_all来提取消息的某些部分,如下所示:

$customerMessage = '"message":"success:2,2;3,3;"' ;
preg_match_all('/("message":")([a-z0-9A-Z]+):([0-9]+,[0-9]+;)+/', $customerMessage, $matches);
var_dump($matches);
die;

此代码输出为:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(27) ""message":"success:2,2;3,3;"
  }
  [1]=>
  array(1) {
    [0]=>
    string(11) ""message":""
  }
  [2]=>
  array(1) {
    [0]=>
    string(7) "success"
  }
  [3]=>
  array(1) {
    [0]=>
    string(4) "3,3;"
  }
}

为什么我不能参与2,2;? 提前谢谢!

1 个答案:

答案 0 :(得分:3)

您只能获得群组的最后一场比赛。两个得到像x,x;这样的所有值,你可以使用你当前的正则表达式,改变一下:

preg_match_all('/("message":")([a-z0-9A-Z]+):(.*)"/', $customerMessage, $matches);
/* $matches[3] --> 2,2;3,3;

现在,您可以使用$matches[3]获取第3组,并将所有x,x;[0-9]+,[0-9]+;匹配

preg_match_all('/[0-9]+,[0-9]+/', $matches[3], $matches2);
/* $matches[0] --> 2,2;
/* $matches[1] --> 3,3;