Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 对模板引擎使用preg_replace()_Php_Preg Replace - Fatal编程技术网

Php 对模板引擎使用preg_replace()

Php 对模板引擎使用preg_replace(),php,preg-replace,Php,Preg Replace,当我试图学习基本模板引擎时,我尝试了不同的代码。我注意到了这个我不理解的问题。 我是新来的,所以任何帮助都将不胜感激 Template.php: class Template { public function render ($template_name) { $path = $template_name . '.php'; if (file_exists($path)) { $contents = file_get_contents($path);

当我试图学习基本模板引擎时,我尝试了不同的代码。我注意到了这个我不理解的问题。 我是新来的,所以任何帮助都将不胜感激

Template.php:

class Template {

public function render ($template_name) {
    $path = $template_name . '.php';

    if (file_exists($path)) {
        $contents = file_get_contents($path);


        $contents = preg_replace('/\{\% for (.+) = (\d+) to (\d+) \%\}/', '<?php for ($$1 = $2; $$1 < $3; $$1++): ?>', $contents);
        $contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $$1; ?>', $contents);
        $contents = preg_replace('/\{\% endfor \%\}/', '<?php endfor ?>', $contents);

        eval(' ?>' . $contents . '<?php ');
    }else{
        exit ('<h1> Template Eror</h1>');
    }
}
}
?>
输出为:

i = 0 
i = 1 
i = 2 
i = 3 
i = 4 
i = 5 
i = 6 
i = 7 
i = 8 
i = 9 
但是在Template.php中,如果
$contents=preg\u replace('/\{\%(.+)\%\}/','',$contents)放在输出显示的“for”“endfor”行之前:

This page isn’t working 
127.0.0.1 is currently unable to handle this request.
HTTP ERROR 500
第二行:

$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $$1; ?>', $contents);
$contents=preg\u replace('/\{\%(.+)\%\}/',''.$contents);

替换每一行
{%endfor%}
,因此第三行永远不会匹配任何
{%endfor%}
,这就是为什么您必须交换这两行。

如果您想创建一个非常基本的模板引擎,那么我只需处理布局并在模板中使用普通的PHP。如果您想创建自己的语法,它将不是很基本,因为会弹出许多您没有考虑过的情况和组合。您还需要添加对函数的支持(如转义输出以防止XSS等)。看起来您所做的一切或多或少只是将
替换为
{%
%}
。看起来您所做的一切或多或少只是替换为{%和%}-我明白了。但是我不明白为什么替换不起作用。替换最后两行会有什么变化/请编辑您的问题,包括
$contents
的一些示例内容,并详细解释“不起作用”的含义。添加两种不同情况下实际发生的情况。
This page isn’t working 
127.0.0.1 is currently unable to handle this request.
HTTP ERROR 500
$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $$1; ?>', $contents);