Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: String to multidimensional array

Tags:

arrays

regex

php

(Sorry for my bad English)

I have a string that I want to split into an array. The corner brackets are multiple nested arrays. Escaped characters should be preserved.

This is a sample string:

$string = '[[["Hello, \"how\" are you?","Good!",,,123]],,"ok"]'

The result structure should look like this:

array (
  0 => 
  array (
    0 => 
    array (
      0 => 'Hello, \"how\" are you?',
      1 => 'Good!',
      2 => '',
      3 => '',
      4 => '123',
    ),
  ),
  1 => '',
  2 => 'ok',
)

I have tested it with:

$pattern = '/[^"\\]*(?:\\.[^"\\]*)*/s';
$return = preg_match_all($pattern, $string, null);

But this did not work properly. I do not understand these RegEx patterns (I found this in another example on this page). I do not know whether preg_match_all is the correct command.

I hope someone can help me.

Many Thanks!!!

like image 595
Vincenz Dreger Avatar asked Oct 18 '22 17:10

Vincenz Dreger


2 Answers

This is a tough one for a regex - but there is a hack answer to your question (apologies in advance).

The string is almost a valid array literal but for the ,,s. You can match those pairs and then convert to ,''s with

/,(?=,)/

Then you can eval that string into the output array you are looking for.

For example:

// input 
$str1 = '[[["Hello, \\"how\\" are you?","Good!",,,123]],,"ok"]';

// replace , followed by , with ,'' with a regex
$pattern = '/,(?=,)/';
$replace = ",''";
$str2 = preg_replace($pattern, $replace, $str1);

// eval updated string
$arr = eval("return $str2;");
var_dump($arr);

I get this:

array(3) {
  [0]=>
  array(1) {
    [0]=>
    array(5) {
      [0]=>
      string(21) "Hello, "how" are you?"
      [1]=>
      string(5) "Good!"
      [2]=>
      string(0) ""
      [3]=>
      string(0) ""
      [4]=>
      int(123)
    }
  }
  [1]=>
  string(0) ""
  [2]=>
  string(2) "ok"
}

Edit

Noting the inherent dangers of eval the better option is to use json_decode with the code above e.g.:

// input 
$str1 = '[[["Hello, \\"how\\" are you?","Good!",,,123]],,"ok"]';

// replace , followed by , with ,'' with a regex
$pattern = '/,(?=,)/';
$replace = ',""';
$str2 = preg_replace($pattern, $replace, $str1);

// eval updated string
$arr = json_decode($str2);
var_dump($arr);
like image 155
Robin Mackenzie Avatar answered Nov 03 '22 04:11

Robin Mackenzie


If you can edit the code that serializes the data then it's a better idea to let the serialization be handled using json_encode & json_decode. No need to reinvent the wheel on this one.

Nice cat btw.

like image 30
Magnavode Avatar answered Nov 03 '22 03:11

Magnavode