PHP regex templating - find all occurrences of {{var}}

后端 未结 3 772
臣服心动
臣服心动 2020-12-04 00:01

I need some help with creating a regex for my php script. Basically, I have an associative array containing my data, and I want to use preg_replace to replace some place-ho

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 00:40

    To not have to use global variables and gracefully handle missing keys you can use

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

提交回复
热议问题