3

I am trying to convert a string to an array when, however, I want to create multidimensional arrays when the string has items in brackets.

For example, if the string as passed: (Mary Poppins) Umbrella (Color Yellow)

I would want to create an array that looks like this:

Array ( [0] => Array ( [0] => mary [1] => poppins) [1] => umbrella [2] => Array ( [0] => color [1] => yellow) )

I was able to get the data placed into an array through this:

preg_match_all('/\(([A-Za-z0-9 ]+?)\)/', stripslashes($_GET['q']), $subqueries); 

But I am having trouble getting the items placed in the multidimensional arrays.

Any ideas?

6
  • 3
    She's called "Mary Poppins" BTW. Commented Jun 7, 2013 at 16:07
  • Use recursion (recursive regexp and recursive funcall) Commented Jun 7, 2013 at 16:08
  • Would there be nested brackets ? hello(cool (foo bar) (troll (attempt baz))) ? Commented Jun 7, 2013 at 16:08
  • 1
    On the off-chance that you are allowed to control the format of the string, JSON notation would be much easier. Commented Jun 7, 2013 at 16:09
  • 3
    You guys, Mary Poppins used a black umbrella. Mary Poppens (with an e), on the other hand, used a yellow umbrella. Please make sure you are familiar with the matter before editing questions that are practically perfect in every way! Commented Jun 7, 2013 at 16:23

1 Answer 1

6

With some PHP-Fu:

$string = '(Mary Poppens) Umbrella (Color Yellow)';
$array = array();
preg_replace_callback('#\((.*?)\)|[^()]+#', function($m)use(&$array){
    if(isset($m[1])){
        $array[] = explode(' ', $m[1]);
    }else{
        $array[] = trim($m[0]);
    }
}, $string);
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [0] => Mary
            [1] => Poppens
        )

    [1] => Umbrella 
    [2] => Array
        (
            [0] => Color
            [1] => Yellow
        )

)

Online demo

Note that you need PHP 5.3+ since I'm using an anonymous function.


Got compatible ?

$string = '(Mary Poppens) Umbrella (Color Yellow)';

preg_match_all('#\((.*?)\)|[^()]+#', $string, $match, PREG_SET_ORDER);

foreach($match as $m){
    if(isset($m[1])){
        $array[] = explode(' ', $m[1]);
    }else{
        $array[] = trim($m[0]);
    }
}

print_r($array);

Online demo

Tested on PHP 4.3+

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply. I should have prefaced. I am on PHP 5.2.x
Still useable, just replace the anonymous function with a regular function and pass the name as a callback
and you really should upgrade to newer versions of PHP !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.