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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?