【问题标题】:Best way to perform lite templating in php with regular expression [duplicate]使用正则表达式在 php 中执行 lite 模板的最佳方法 [重复]
【发布时间】:2018-09-14 20:52:00
【问题描述】:

您好,我正在尝试在 PHP 中执行一个非常简单的模板系统。

我愿意这样做:

  • 读取一些 .md 文件
  • 用数组中的对应变量更改所有 {{ variables }}

    $data( array('variable1' => 'value', 
                 'variable2' => 'value2'));
    
  • 管理变量不存在的情况,以防止出现“key not found in array”之类的错误。

目前我已经这样做了(不是在正则表达式中,它也不起作用)

class Markdown{
    private static $folder = 'markdowns/';

    public static function fill_template($template, $array){

        $text = file_get_contents(self::$folder . $template . '.md'); 
        foreach($array as $key => $value){
            $text = str_replace('{{'.$key.'}}', $value, $text);
        }

        return $text;
    }
}

有什么想法吗?

谢谢

【问题讨论】:

    标签: php regex templating


    【解决方案1】:

    您可以使用preg_replace_callback() 将模式{{variable}} 转换为其对应的值:

    public static function fill_template($template, $array){
        $text = file_get_contents(self::$folder . $template . '.md');
        $text = preg_replace_callback('~\{\{([^}]+)\}\}~', function($matches) use ($array) {
            $key = trim($matches[1]); // remove unwanted spaces
            if (isset($array[$key])) return $array[$key]; // return the value if found
            // If not found, return the key:
            return $key;
        }, $text);
        return $text;
    }
    

    如果在数组中没有找到匹配的内容,则返回不带{{}}的内容。

    正则表达式:

    ~       # delimiter
    \{\{    # two literal { - need to be escaped
    (       # start capture group
     [^}]+  # all character until }
    )       # end capture group
    \}\}    # two literal } - need to be escaped
    ~       # end delimiter
    

    【讨论】:

      【解决方案2】:

      您可以使用preg_replace_callback 获得简单的渲染器

      function render($template, $vars) {
          return \preg_replace_callback("!{{\s*(?P<key>[a-zA-Z0-9_-]+?)\s*}}!", function($match) use($vars){
              return isset($vars[$match["key"]]) ? $vars[$match["key"]] : $match[0];
          }, $template);
      }
      

      例子

      echo render(
          "Hello {{ name  }}, how are you today? Date: {{time   }} and it's {{weather}} in {{location}}\n", 
          ["name"=>"World!!", "time"=>date("c")]
      );
      

      将渲染到

      Hello World!!,你今天好吗?日期:2018-04-05T06:40:34+00:00 是 {{location}} 的 {{weather}}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 2015-02-25
        • 2023-03-23
        相关资源
        最近更新 更多