kasakka
kasakka

Reputation: 838

PHP: Parsing string into array with nested arrays?

I've got the following code for parsing a string into an array of options:

$options = 'myvalue, test=123, myarray=[1,2]';

function parse_options($options)
{
    $split = '/,(?=[^\]]*(?:\[|$))/';

    if($options && is_string($options)) 
    {
        $temp_options = preg_split($split, $options);
        $options = array();
        foreach($temp_options as $option) 
        {
            $option = trim($option);
            if(strpos($option,'=')) 
            {
                //Is an option with a value
                list($key, $value) = explode('=',$option);
                if(strpos($value,'[') !== FALSE) 
                {
                    //Is an array of values
                    $value = explode(',', substr($value, 1,-1));
                }
                $options[$key] = $value;
            }
            else 
            {
                $options[] = $option;
            }
        }
    }
    else 
    { 
        //Return empty array if not a string or is false
        if(!is_array($options)) { $options = array(); }
    }

    return $options;
}

Basically it splits by comma unless surrounded by brackets. Then it checks for the = for key->value pairs and then tries to figure out if the value is an array.

This works fine, but I would like to improve it so that it can create nested arrays for something like

$options = 'myvalue, test=123, bigwhopper=[ myarray=[1,2], test2=something ]';

Which would output

Array(
    [0] => myvalue,
    [test] => 123,
    [bigwhopper] => Array(
                [myarray] = Array(
                     [0] => 1,
                     [1] => 2
                ),
                [test] => something
            )
)

I'm certainly no RegExp guru so can someone help me make the function understand nested [] separators? Also anything to improve the function's performance is highly appreciated as I use this a lot to easily pass options to my controllers.

Upvotes: 0

Views: 320

Answers (2)

Ugo Méda
Ugo Méda

Reputation: 1215

Don't reinvent the wheel by creating a new (incomplete, buggy and slow) parser for your options. Use preexisting solutions :

Upvotes: 0

Evert
Evert

Reputation: 99525

Why are you inventing your own format, over something that's already widely established.

Some options:

  • urlencoding does this
  • json
  • yalm
  • php's serialize()

You're inventing a whole new syntax, and standard regex won't even allow this because it has recursion. You basically need to write a parser, so the best place to start if you insist on your own syntax, is to look at parser generators.

http://wezfurlong.org/blog/2006/nov/parser-and-lexer-generators-for-php/

Upvotes: 1

Related Questions