概述:我正在为我的网站制作一个诱人的系统,目前运行良好,并且按照我的预期运行,唯一的问题是当我想要显示 {PAGE_SIDEBAR} 之类的内容时文件 template/sidebar.php 或类似的东西。
我正在使用
//loads of other str_replace here
$body = str_replace("{PAGE_SIDEBAR}, include("template/sidebar.php"), $body);
echo $body;
这是有效的,但是它在正文的开头包含文件,而不是 {PAGE_SIDEBAR} 所在的位置。标记所在的位置显示数字 1。
查看截图以获得更好的解释:
How the rendered template looks before
此外,对于兴趣点,使用 file_get_contents() 而不是 include() 的外观:http://www.jamesmoorhouse.co.uk/stack_overflow/str_replace/file_get_contents_method.png
理想情况下,我希望它能像使用 include 方法一样工作,但会显示在 file_get_contents 方法放置它的位置。
最佳答案
您必须使用 output buffering 捕获 include
输出的所有内容能够将其用作字符串:
ob_start();
include("template/sidebar.php");
$str_sidebar = ob_get_clean();
$body = str_replace("{PAGE_SIDEBAR}", $str_sidebar, $body);
echo $body;
如果有许多要替换的占位符,您可能需要使用基于正则表达式的解决方案和回调,这样您就不必为每个占位符重复此代码。看我的回答here用于入门。
关于PHP str_replace 将函数/文件包含为模板系统的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11327591/