dongyi1441 2017-03-21 16: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-21 16: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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部