3

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.

2
  • Well, I already answered, but is ['twi'=>'ter','link'=>'edin'] and others a STRING or should they define an actual array? Commented May 19, 2015 at 15:46
  • No they all should go as string. Commented May 19, 2015 at 16:02

2 Answers 2

4

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']
)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Seems like you have an evil() day today :)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.