duanji1899 2015-11-23 21:55
浏览 270
已采纳

PHP:在字符串变量中交换占位符以获取相应的已定义变量值

I have a PHP script with some variables set in the global namespace:

$domain = 'example.com';
$hostname = 'www.' . $domain;

I am reading an external file into a string variable in my script using file_get_contents:

$file_contents = file_get_contents('external_file.tpl');

The external file (and the string $file_contents) contains placeholders which correspond to variable names.

127.0.0.1 {{domain}} {{hostname}}

I would like to have all the placeholders in the variable $file_contents replaced with their respective PHP variables already set. I want this to work generically (without hard-coding placeholder / variable names). I do not want to edit the file, just the contents of the string.

What's the easiest way to do this?

  • 写回答

6条回答 默认 最新

  • doulu1020 2015-11-23 22:43
    关注

    Alright guys, I took some bits and pieces from other answers and came up with what I think is the best solution for me:

    $domain = 'example.com';
    $hostname = 'www.' . $domain;
    $file_contents = '127.0.0.1 {{domain}} {{hostname}}';
    
    $result = preg_replace_callback(
        "/{{(.+?)}}/",
        function ($matches) {
            return $GLOBALS[$matches[1]];
        },
        $file_contents
    );
    

    This answer combines ideas from @TonyDeStefano, @dops, and @fschmengler. So please up-vote them. @BugaDániel also helped with his comments.

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

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1