在php文件中替换{{string}}

jku*_*ner 12 php variables replace

我在我的一个类方法中包含一个文件,并且在该文件中有html + php代码.我在该代码中返回一个字符串.我明确写了{{newsletter}},然后在我的方法中我做了以下:

$contactStr = include 'templates/contact.php';
$contactStr = str_replace("{{newsletter}}",$newsletterStr,$contactStr);
Run Code Online (Sandbox Code Playgroud)

但是,它不是替换字符串.我这样做的唯一原因是因为当我尝试将变量传递给包含的文件时,它似乎无法识别它.

$newsletterStr = 'some value';
$contactStr = include 'templates/contact.php';
Run Code Online (Sandbox Code Playgroud)

那么,我该如何实现字符串替换方法呢?

bit*_*ing 36

您可以使用PHP作为模板引擎.不需要{{newsletter}}构造.

假设您$newsletter在模板文件中输出变量.

// templates/contact.php

<?php echo $newsletter; ?>
Run Code Online (Sandbox Code Playgroud)

要替换变量,请执行以下操作:

$newsletter = 'Your content to replace';

ob_start();        
include('templates/contact.php');
$contactStr = ob_get_clean();

echo $contactStr;

// $newsletter should be replaces by `Your content to replace`
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以构建自己的模板引擎.

class Template
{
    protected $_file;
    protected $_data = array();

    public function __construct($file = null)
    {
        $this->_file = $file;
    }

    public function set($key, $value)
    {
        $this->_data[$key] = $value;
        return $this;
    }

    public function render()
    {
        extract($this->_data);
        ob_start();
        include($this->_file);
        return ob_get_clean();
    }
}

// use it
$template = new Template('templates/contact.php');
$template->set('newsletter', 'Your content to replace');
echo $template->render();
Run Code Online (Sandbox Code Playgroud)

关于它的最好的事情:您可以立即在模板中使用条件语句和循环(完整的PHP).

  • 如果你想保护包含的文件免受可变污染(*即`$ this`*)你可以将它包装在一个反弹闭包中:`call_user_func(Closure :: bind(function(){include func_get_arg(0);},null ),$ path);` (3认同)

da-*_*ype 14

这是我用于模板的代码,应该做的伎俩

  if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
      foreach ($m[1] as $i => $varname) {
        $template = str_replace($m[0][$i], sprintf('%s', $varname), $template);
      }
    }
Run Code Online (Sandbox Code Playgroud)

  • 实际上它看起来应该是sprintf('%s',$$ varname) (2认同)

Oct*_*tal 6

也许有点晚了,但我看起来像这样。

问题是 include 不返回文件内容,更简单的解决方案是使用 file_get_contents 函数。

$template = file_get_contents('test.html', FILE_USE_INCLUDE_PATH);

$page = str_replace("{{nombre}}","Alvaro",$template);

echo $page;
Run Code Online (Sandbox Code Playgroud)


小智 5

基于@da-hype

<?php
$template = "hello {{name}} world! {{abc}}\n";
$data = ['name' => 'php', 'abc' => 'asodhausdhasudh'];

if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
    foreach ($m[1] as $i => $varname) {
        $template = str_replace($m[0][$i], sprintf('%s', $data[$varname]), $template);
    }
}


echo $template;
?>
Run Code Online (Sandbox Code Playgroud)