stuck
stuck

Reputation: 1560

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.

Upvotes: 0

Views: 75

Answers (3)

Lessmore
Lessmore

Reputation: 1091

use json_decode but first replace quotes to double quotes:

json_decode(str_replace('\'','"',$content));

Upvotes: 3

AbraCadaver
AbraCadaver

Reputation: 78994

For completeness, that is a valid PHP array definition also:

eval("\$results = $content;");

// or

eval('$results = ' . $content . ';');

Then $results will be that array.

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94662

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
        )

)

Upvotes: 2

Related Questions