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.

56

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.

573

Answer

Solution:

If it helps you:

$string = '{$myVariable:trim:substr,1,2}';

if (preg_match("#^\{\\$([a-zA-Z]+)\:([a-z]+)\:([a-z]+)\,([0-9]+)\,([0-9]+)\}$#", $string, $m)){
$result = <<<RESULT
Array (
    "{$m[1]}",
    Array (
        "{$m[2]}" => Array(),
        "{$m[3]}" => Array(
            {$m[4]},
            {$m[5]}
        )
    )
)
RESULT;
}
echo $result;

People are also looking for solutions to the problem: php - Function Netbeans Include Path

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.