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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度