Search code examples
phpregexphp-5.3

parsing string into array (['class': 'navigation', 'id': 'navigation'])


Anyone can suggest an alternative method to parse a string: (['class': 'navigation', 'id': 'navigation']).

I used to use:

if(strpos($match[1], '[') === 0)
{
    $render = array();

    foreach(explode(',', substr($match[1], 1, -1)) as $arr)
    {
        $parts  = explode(':', $arr);

        if(count($parts) == 2)
        {
            $render[substr(trim($parts[0]), 1, -1)] = substr(trim($parts[1]), 1, -1);
        }
        else
        {
            $render[]   = substr(trim($parts[0]), 1, -1);
        }
    }

    $args[] = $render;
}
elseif(strpos($match[1], "'") == 0)
{
    $args[] = substr($match[1], 1, -1);
}

However, it doesn't take long to understand the drawbacks of this method, e.g. ['title': 'Tom's diary'] would completely fail the code.

It would also nice to be able to identify an erroneous entries and leave them out. At the moment all I do is use: |{{([^}]+)}}| to catch all functions, which look like: {{foo}}, {{foo('test', 'best')}} or {{foo(['array': 'bar'])}}. If you have quick solution, I'd appreciate if you share it.


Solution

  • Your string's format seems not too far from JSON -- even if it doesn't seem to be real JSON (you are using [] instead of {}, arround what seems to be an object).

    Maybe you could change your format, in order to use JSON ?


    That would allow you to use the [**`json_encode()`**][2] and [**`json_decode()`**][3] functions.

    And more people would be able to work with your data, as you'd be using a standard format.