【问题标题】:php: how to replace all string values by variables values?php:如何用变量值替换所有字符串值?
【发布时间】:2016-03-15 23:15:04
【问题描述】:

我正在使用那种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

【问题讨论】:

  • 您是否考虑过使用 Twig 之类的东西而不是重新发明轮子? ;)
  • 通过HEREDOC 定义可以更轻松、更优雅地解决此任务,但模板的语法必须稍有不同:php.net/manual/en/…
  • <?=$username?>代替{{username}}怎么样?
  • 您可以考虑将所有的 '{{' 替换为 '$' 和 '}}' 替换为 ''。如果你使用 vim 编辑器试试这个: :%s/{{/$/gc :%s/}}//gc

标签: php arrays loops replace


【解决方案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

【讨论】:

    【解决方案2】:

    试试这个。

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 2014-06-12
      • 2018-12-30
      • 1970-01-01
      • 2018-01-01
      • 2019-11-24
      • 2022-12-10
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多