Skip to content
Advertisement

String to Multi-Dimensional array in PHP

Imagine that I have a variable that contains following value:

$content = "[['a', 'b', 1, 4], ['a2', 'b2', 12, 42], ['a3', 'b3', 13, 43], ['a4', 'b4', 14, 44]]";

I want to parse this string and create actual multi-dimensional array in PHP. For example:

Array
(
    [0] => Array
        (
            [0] => 'a'
            [1] => 'b'
            [2] => 1
            [3] => 4
        )

    [1] => Array
        (
            [0] => 'a2'
            [1] => 'b2'
            [2] => 12
            [3] => 42
        )
    [2] => Array
        (
            [0] => 'a3'
            [1] => 'b3'
            [2] => 13
            [3] => 43
        )

    [3] => Array
        (
            [0] => 'a4'
            [1] => 'b4'
            [2] => 14
            [3] => 44
        )
)

For that purpose, first of all I tried to parse that string via regular expression:

$pattern = "/[([.+])]/i";

However I failed when I tried it as following:

$pattern = "/[([.+])]/i";
$content = "[['a', 'b', 1, 4], ['a2', 'b2', 12, 42], ['a3', 'b3', 13, 43], ['a4', 'b4', 14, 44]]";

preg_match_all($pattern, $content, $results);

print_r($results);

And the output is:

Array ( 
    [0] => Array ( [0] => [['a', 'b', 1, 4], ['a2', 'b2', 12, 42], ['a3', 'b3', 13, 43], ['a4', 'b4', 14, 44]] ) 
    [1] => Array ( [0] => ['a', 'b', 1, 4], ['a2', 'b2', 12, 42], ['a3', 'b3', 13, 43], ['a4', 'b4', 14, 44] ) 
) 

So;

  1. How can I solve that regex issue?
  2. Are there any other ways to implement that problem?

Thanks.

Advertisement

Answer

Convert it to JSON, which is simple all you need to do is replace the single quotes with double quotes, then it will be a JSON String

$content = "[['a', 'b', 1, 4], ['a2', 'b2', 12, 42], ['a3', 'b3', 13, 43], ['a4', 'b4', 14, 44]]";
$c = str_replace("'", '"', $content);

print_r(json_decode($c));

Result

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => 1
            [3] => 4
        )

    [1] => Array
        (
            [0] => a2
            [1] => b2
            [2] => 12
            [3] => 42
        )

    [2] => Array
        (
            [0] => a3
            [1] => b3
            [2] => 13
            [3] => 43
        )

    [3] => Array
        (
            [0] => a4
            [1] => b4
            [2] => 14
            [3] => 44
        )

)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement