String with Key/Value-Syntax to Multidimensional Array

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Vamporio
Forum Newbie
Posts: 1
Joined: Tue Apr 24, 2012 7:53 am

String with Key/Value-Syntax to Multidimensional Array

Post 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'
   )
  )
);
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

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

Post 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()
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply