PHP preg_match_all获取短标记之间的变量名称

I have template files which use short tags <?= $some_var; ?>. I need to write a script to get a list of the variables used in that template, i.e. an array like:

[
    0 => '$some_var',
    ...
    n => '$some_var_n'
]

I have tried:

preg_match_all('/<?[^p](.*)?>/s', $file_contents, $matches);

and some other various combinations but to no luck.

Thanks.

You need to escape the ?s, otherwise they make the preceding character/group optional. You also can make the regex stricter and use the regex for valid variable names PHP provides(http://php.net/manual/en/language.variables.basics.php).

Something like:

<\?=\h+(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+);?\h*\?>

should find your variables.

Demo: https://regex101.com/r/fVBZAS/1/

With token_get_all:

function genTempVar($text) {
    $open = false;
    foreach (token_get_all($text) as $v) {
        if ( $open ) {
            if ( $v[0] == T_CLOSE_TAG ) $open = false;
            elseif ( $v[0] == T_VARIABLE ) yield $v[1];
        } elseif ( $v[0] == T_OPEN_TAG_WITH_ECHO ) $open = true; 
    }
} 

print_r(iterator_to_array(genTempVar($text)));