PHP parsing string into array with regex
I have a line like this:
$msg,array('goo','gle'),000,"face",'book',['twi'=>'ter','link'=>'edin']
I want to use preg_match_all to convert it to an array that might look like this:
array(
0 => $msg,
1 => array('goo','gle'),
2 => 000,
3 => "face",
4 => 'book',
5 => ['twi'=>'ter','link'=>'edin']
);
Note that all values are string .
I'm not very good at regex, so I just couldn't create a Template to do this. Multiple calls to preg will also be made.
+3
source to share
2 answers
I suggest using preg_split
with the following regex:
$re = "/([a-z]*(?:\\[[^]]*\\]|\\([^()]*\\)),?)|(?<=,)/";
$str = "\$msg,array('goo','gle'),000,\"face\",'book',['twi'=>'ter','link'=>'edin']";
print_r(preg_split($re, $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
Sample program output :
Array
(
[0] => $msg,
[1] => array('goo','gle'),
[2] => 000,
[3] => "face",
[4] => 'book',
[5] => ['twi'=>'ter','link'=>'edin']
)
+4
source to share