Search code examples
phpregexpreg-match-allstrpos

regex problem with PHP


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.


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.