Question

i want to parse a template file and find a specific set of variables that look like that:

<!-- [LOOP-VARIABLENAME] -->

i just want to get the variablename and the starting position of the match. first i used strpos(), but this is function is unable to take a regex argument.

Array (
  [0] => 1678 // strpos
  [1] => <!-- [LOOP-VARIABLENAME] --> // full match
  [name] => VARIABLENAME
)

is this possible? i tried to use this regex:

preg_match_all('/<!-- [LOOP-(?P<year>\W+)/', $html, $matches, PREG_OFFSET_CAPTURE);

but no positive result.

thanks for your help.

Was it helpful?

Solution

<?php

$html = "jg<!-- [LOOP-VARIABLENAME] -->sdfsdfsdf<!-- [LOOP-TESTNAME] -->sfdsdffsd";

preg_match_all('/<!-- \[LOOP-(\w+)]\ -->/', $html, $matches, PREG_OFFSET_CAPTURE);

echo '<pre>' . print_r($matches, true) . '</pre>';

?>

This code gives output like this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 
                    [1] => 2 //position where matching <!-- starts, 1st var
                )

            [1] => Array
                (
                    [0] => 
                    [1] => 39  //position where matching <!-- starts, 2nd var
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => VARIABLENAME
                    [1] => 13  //position where VARIABLENAME starts
                )

            [1] => Array
                (
                    [0] => TESTNAME
                    [1] => 50 //position where TESTNAME starts
                )

        )

)

If that array doesn't look quite how you want it to, I can write some more code to transform it.

OTHER TIPS

Looks like you're not escaping your special characters.. for example,

[LOOP

should be

\[LOOP

in your regex pattern.

thanks for your reply, but tried this already

preg_match_all('/<!-- \[LOOP-(?P<name>\W+)/', "<!-- [LOOP-VARIABLENAME] -->", $matches, PREG_OFFSET_CAPTURE);

print_r($matches);

the output looks like this:

Array ( [0] => Array ( ) [name] => Array ( ) [1] => Array ( ) ) Array ( [0] => Array ( ) [name] => Array ( ) [1] => Array ( ) )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top