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;
- How can I solve that regex issue?
- Are there any other ways to implement that problem?
Thanks.
question from:
https://stackoverflow.com/questions/65646610/string-to-multi-dimensional-array-in-php