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

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了