dongyi1441 2017-03-22 00:00 采纳率: 100%
浏览 33
已采纳

从PHP中的文本文件中提取变量

I've had a good search and not found anything relevant to my issue, so please dont down vote without showing me where you have a relevant example...

Trying to build template files as a text document to simplify it for others to modify later, but I can't work out how to get PHP to recognize the variables in it.

What I want to work:

//template.txt
Every time I find $foo,
I get a little $bar,
template text.

note: The line breaks are critical for position.

//handler.php
$foo = 'Beer';
$bar = 'Excited';
$file = file('template.txt');

foreach ($file as $line) {
    echo $line;
}

What I want this to return:

Every time I find Beer,
I get a little Excited,
template text.

but it is escaping the variable mark ($), and is returning:

Every time i find $foo,
I get a little $bar,
template text.

I tried to do a str replace with:

if (strpos($line, '\$foo')) {
    str_replace('\$foo', $foo, $line);
}

(tried with and without the $ symbol, and many variations on this) at best I can get it to recognise the variable name but it is not replacing.

Has anyone had any experience with this?

Really not finding much info on this online. Any help will be greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dtby67541 2017-03-22 00:03
    关注

    When you're using single quote it's auto escaping everything in there, so you're telling it to replace \$foo not $foo

    str_replace('$foo', $foo, $line);
    

    Also you don't really need the if statement, if it can't find it it's not going to do anything anyway.

    If you're going to have more variables you could set up a pair of arrays and instead of iterating through it line by line just throw the whole string at it at once

    $file = file('template.txt');
    $search = array('$foo', '$bar');
    $replace = array('Beer', 'Excited');
    $file = str_replace($search, $replace, $file);
    foreach ($file as $i) {
        echo $i;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题