简体   繁体   中英

PHP preg_match_all get name of variable between short tags

I have template files which use short tags <?= $some_var; ?> <?= $some_var; ?> . I need to write a script to get a list of the variables used in that template, ie 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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM