Abadis Abadis - 5 days ago 6
PHP Question

php preg_match_all Not getting all results

I am using php

preg_match_all
to extract some parts of a message like this:

$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;


this code output is:

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;"
}
}


Why cant I get part
2,2;
?
Thanks in advance!

Answer

You can only get the last match of a group. Two get all values like x,x; you can use your current regex, changed a bit:

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

Now you can get group 3 with $matches[3] and match all x,x; with [0-9]+,[0-9]+;

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