dongyu5104 2012-02-04 15:41
浏览 65
已采纳

preg_replace使用替换的文本作为变量名称

I have several variables like these:

$foo = '123';  
$bar = 'bqwe';

I need to replace {$foo} and {$bar} in a string with the variables.

preg_replace('~\{\$(.*)?\}~sU', ${'\\1'}, $string);

This doesn't work.

PS: The regex might not be correct. I haven't tested it with several variables like {$asd} {$bbb}. I am testing with one variable now.

  • 写回答

3条回答 默认 最新

  • dronthpi05943 2012-02-04 15:54
    关注

    You should make the regex more specific. Make it match for \w+ word characters.

    And then you were on the right track, but need the /e eval modifier to make the variable lookup in the local scope work:

    = preg_replace('~\{\$(\w+?)\}~sUe', '${"$1"}', $string);
    

    So when it matches foo the relacement string becomes ${"foo"} which then is used as expression. (Whereas in your original code it was incorrectly tried before the regex executed.)

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

报告相同问题?

悬赏问题

  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)