I have a string like this:
$msg,array('goo','gle'),000,"face",'book',['twi'=>'ter','link'=>'edin']
I want to use preg_match_all to convert this to an array that could look like this:
array(
0 => $msg,
1 => array('goo','gle'),
2 => 000,
3 => "face",
4 => 'book',
5 => ['twi'=>'ter','link'=>'edin']
);
Note that all the values are string .
I am not very good at regular expressions, so I have just been unable to create a Pattern for this. Multiple preg calls will also do.
AbraCadaver
79.2k7 gold badges75 silver badges91 bronze badges
asked May 19, 2015 at 15:26
anwerj
2,4982 gold badges20 silver badges39 bronze badges
2 Answers 2
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));
Output of the sample program:
Array
(
[0] => $msg,
[1] => array('goo','gle'),
[2] => 000,
[3] => "face",
[4] => 'book',
[5] => ['twi'=>'ter','link'=>'edin']
)
answered May 19, 2015 at 15:40
Wiktor Stribiżew
631k41 gold badges503 silver badges633 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I know you asked for a regular expression solution, however I'm on an eval() kick today:
eval('$array = array('.$string.');');
print_r($array);
Also note that 000 is NOT a string and will be converted to 0.
answered May 19, 2015 at 15:44
AbraCadaver
79.2k7 gold badges75 silver badges91 bronze badges
1 Comment
Rizier123
Seems like you have an
evil() day today :)?lang-php
['twi'=>'ter','link'=>'edin']and others a STRING or should they define an actual array?