首页 > 解决方案 > Using preg_replace() for template engines

问题描述

As i am trying to learn about basic template engines, i was trying out different codes. And i noticed this issue that i don't understand. i am new, so any help would be appreciated.

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>');
    }
}
}
?>

test.php :

    {% for i = 0 to 10 %}
        <b> i = {% i %}  </b><br>
    {% endfor %}

index.php :

include 'Template.php';

$template = new Template;

$template->render('myTemplate');

the output is:

i = 0 
i = 1 
i = 2 
i = 3 
i = 4 
i = 5 
i = 6 
i = 7 
i = 8 
i = 9 

But in Template.php if $contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $$1; ?>', $contents); is placed before either 'for' 'endfor' lines the output shows :

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

标签: phppreg-replace

解决方案


第二行:

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

替换每个 {% endfor %}所以第三行永远不会匹配任何{% endfor %}这就是为什么你必须交换这两行。


推荐阅读