PHP - Parse template variable with regex
647
I have to parse this template file ($html) :
{$myFirstVariable}
{$myMainVar:MYF1,"x\:x\,x",2:MYF2:MYF3,false}
{$myLastVariable:trim}
Following, my php parser :
$regexp = '#{\$(?<name>.+?)(\:(?<modifiers>.+?))?}#';
preg_replace_callback($regexp, 'separateVariable', $html);
function separateVariable($matches) {
$varname = $matches['name'];
print $varname."\n";
if (isset($matches['modifiers'])) {
$modifiers = $matches['modifiers'];
$modifiers = preg_split('#(?<!\\\):#', $modifiers);
$parsed = array();
foreach ($modifiers as $modifier) {
$modifier = preg_split('#(?<!\\\),#', $modifier);
$parsed[array_shift($modifier)] = $modifier;
}
// parsed[myFuncName] = Array(2ndArg, 3rdArg)
print_r($parsed);
}
print "\n";
}
All working except i've to escape ':' and ',' in {$myMainVar:...} with an '\'.
Do you have any solution to free me up of '\' ?
Thanks.
Answer
Solution:
Regular expression can't return nested array, besides, what you are trying to seems more that text processing (
,
..) than having to use regular expression. Also, your example doesn't make it clear how is the standard processing of the input works.
I suggest: Building a recursive function that deals with the logic of your
unserialiing
process, that function will use switch cases and string manipulation functions.Answer
Solution:
Regex won't help you too much with this because the data has multiple levels. It might be easier to split the data first by
:
and then parse the result (i.e. now splitsubstr,1,2
by,
). The problem is that you would need multiple Regexes. Regexes don't return arrays and they don't do multidimensional matches; they are used for parsing fields from data whose format is known ahead of time.Answer
Solution:
If it helps you: