php:如何用变量值替换所有字符串值?

时间:2015-12-10 10:46:03

标签: php arrays loops replace

我正在使用那种html模板:

Hello {{username}}, my email is {{email}} and my age is {{age}}

({{variables}}的数量是动态的)

我想自动解析模板并用php变量内容替换所有{{variables}}

前:

$username="Peter"; $email="myemail";$age=20;

所以它应该呈现如下:

$res = render("template.html", array("username"=>$username, email=>$email, age=>$age));
彼得,你好;我的电子邮件是myemail,我的年龄是20岁

2 个答案:

答案 0 :(得分:1)

你可以这样做:

function render($template, $vars) {
    $template = file_get_contents($template);
    $search  = [];
    $replace = [];
    foreach ($vars as $key => $value) {
        $search[] = '{{'.$key.'}}';
        $replace[] = $value;
    }
    return str_replace($search, $replace, $template);
}

虽然如果你想要更复杂,你应该使用像Handlebars这样的东西:

https://github.com/zordius/lightncandy

https://github.com/XaminProject/handlebars.php

答案 1 :(得分:0)

试试这个。

function render($template,$values){
    $data=file_get_contents('templates/'.$templates); //templates/ is just templates path. you can change it.

    foreach ($values as $key => $value) {
        $data=str_replace('{{'.$key.'}}', $value, $data);
    }

    return $data;
}