php - 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
解决方案
第二行:
$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $$1; ?>', $contents);
替换每个 {% endfor %}
所以第三行永远不会匹配任何{% endfor %}
这就是为什么你必须交换这两行。
推荐阅读
- r - 将向量的所有元素乘以R中for循环中的每个元素
- javascript - Javascript - 单击不同按钮时单击具有类或 id 的多个元素
- aws-lambda - CloudWatch Insights:获取错误 lambda 的日志
- python - 每个测试禁用带有注释或内联的 Pytest 捕获
- javascript - Javascript如何在使用时区时逐日验证getDay
- git - 如何修复 gitignore 中的 .vscode 跟踪
- python-3.x - 使用鼠标事件向绘图添加一个点
- c# - Unity 为什么我的 FPS 暂停菜单不会停止相机旋转?
- c++ - 如何在 C++ 中的两点之间插入“k”个点?
- php - 如何使用php从mysql中的多列搜索中获取记录