Page 1 of 1

String with Key/Value-Syntax to Multidimensional Array

Posted: Tue Apr 24, 2012 8:08 am
by Vamporio
Hey guys,
I am searching for a regex in combination with php-recursion to parse a string with a nested key/value-syntax as multidimensional array. Has anybody an idea how I can get that done? THANX FOR ANY HELP!

Code: Select all

$string = "value1 | key2=value2 | [value3.1 | key3.2=value3.2 | key3.3=[key3.3.1=value3.3.1]]";

$result = parseSyntax($string);

// RESULT
//===============================================
array(
 '0' => 'value1',
 'key2' => 'value2',
 '1' => array(
  '0' => 'value3.1',
   'key3.2' => 'value3.2',
   'key3.3' => array(
     'key3.3.1' => 'value3.3.1'
   )
  )
);

Re: String with Key/Value-Syntax to Multidimensional Array

Posted: Tue Apr 24, 2012 11:27 am
by pickle
Oh geez. I don't envy you.

I don't think this can be done with a regex - at all. Too many conditions. I'd suggest coming up with some tokenizing functionality, ie: when a | is encountered, that's a new item, when [ is encountered, that's a new array, etc.

Best of luck.

P.S. It looks like the string was someone's attempt to serialize an array. Is there any chance you can change the format of the string? If so, might I suggest serialize()/unserialize(), or if human readability is an issue, json_encode()/json_decode()