Created
January 3, 2012 04:47
-
-
Save anonymous/1553533 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function parse( $string ) { | |
$string = trim($string); | |
//if the string starts with a '@' then we're starting a new array, which may have multiple parts: | |
if ( substr($string, 0, 1) == '@' ) { | |
//find the first key in the array: | |
preg_match("/^@\[([^\]]+)\]/", $string, $foo); | |
$key = $foo[1]; | |
//split the string on the first key to get all the keys of the "parent" array: | |
$parts = explode( "@[{$key}]", $string ); | |
//kill the first part, it's empty | |
unset($parts[0]); | |
//build the array: | |
$results = array( $key => array() ); | |
foreach ( $parts as $part ) { | |
$parse = parse($part); | |
foreach ( $parse as $k => $v ) { | |
$results[$key][$k] = $v; | |
} | |
} | |
return $results; | |
} | |
//ok, we're not starting a new array. we must be at another key: | |
elseif ( substr($string, 0, 1) == '[' ) { | |
//find the key: | |
preg_match("/^\[([^\]]+)\]/", $string, $foo); | |
$key = $foo[1]; | |
//no need to find the parts, there aren't repeats of this key: | |
//get the existing key out of there: | |
return array( $key => parse( preg_replace("/^\[" . preg_quote($key) . "\]/", '', $string) ) ); | |
} | |
//not a new array and not a key, must be a straight assignment: | |
elseif ( substr($string, 0, 1) == '=' ) { | |
//find the value to assign: | |
preg_match("/^=\s*([^\@\[]+)/", $string, $foo); | |
return trim($foo[1]); | |
} | |
//unhandled condition: | |
else { | |
die("UNHANDLED:\n\t{$string}\n\n"); | |
} | |
} | |
print_r( parse( "@[item_1][door] @[mozart][grass] = yes @[mozart][green] = no @[mozart][human] @[blue][movie]=yes @[item_1][beat] = yes @[item_1][music] = no " ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment