dopgl80062 2017-04-24 12:07
浏览 80
已采纳

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.

  • 写回答

2条回答 默认 最新

  • douchou8935 2017-04-24 12:24
    关注

    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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?