Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Converting a string to an multidimensional array

Tags:

php

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?

like image 887
zeropsi Avatar asked Dec 14 '25 05:12

zeropsi


1 Answers

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+

like image 54
HamZa Avatar answered Dec 15 '25 19:12

HamZa