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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效