>我有这样的文件
**buffer.php**
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
ob_end_flush();
缓冲区内的所有内容都是使用数据库中的数据动态制作的。将 php 插入数据库不是一种选择。
问题是,我得到了我的输出缓冲区,我想用一个有效的 php include 替换"{replace}",其中包括一个也有一些 html/php 的文件。
所以我的实际问题是:如何在输出缓冲区中用有效的 php 代码替换字符串?
我希望你能帮忙,已经用了很多时间。
最好的问候 - user2453885
编辑 - 25/11/14
我知道wordpress或joomla正在使用一些类似的功能,你可以在你的帖子中写{rate},它用评级系统(一些rate插件)代替它。这就是我想要的秘密知识。
您可以使用
preg_replace_callback,让回调包含要包含的文件并返回输出。或者你可以用文本包含替换占位符,将其保存为文件并包含该文件(有点编译东西)
对于简单的文本,你可以进行分解(尽管对于大块文本来说可能不是最有效的):
function StringSwap($text ="", $rootdir ="", $begin = "{", $end = "}") {
// Explode beginning
$go = explode($begin,$text);
// Loop through the array
if(is_array($go)) {
foreach($go as $value) {
// Split ends if available
$value = explode($end,$value);
// If there is an end, key 0 should be the replacement
if(count($value) > 1) {
// Check if the file exists based on your root
if(is_file($rootdir . $value[0])) {
// If it is a real file, mark it and remove it
$new[]['file'] = $rootdir . $value[0];
unset($value[0]);
}
// All others set as text
$new[]['txt'] = implode($value);
}
else
// If not an array, not a file, just assign as text
$new[]['txt'] = $value;
}
}
// Loop through new array and handle each block as text or include
foreach($new as $block) {
if(isset($block['txt'])) {
echo (is_array($block['txt']))? implode(" ",$block['txt']): $block['txt']." ";
}
elseif(isset($block['file'])) {
include_once($block['file']);
}
}
}
// To use, drop your text in here as a string
// You need to set a root directory so it can map properly
StringSwap($text);
我可能在这里误解了一些东西,但像这样简单的事情可能会起作用?
<?php
# Main page (retrieved from the database or wherever into a variable - output buffer example shown)
ob_start();
<h1>Welcome</h1>
{replace_me_with_working_php_include}
<h2>I got a problem..</h2>
$main = ob_get_clean();
# Replacement
ob_start();
include 'whatever.php';
$replacement = ob_get_clean();
echo str_replace('{replace_me_with_working_php_include}', $replacement, $main);
如果您也希望从该任务中删除输出缓冲区,也可以从包含文件中使用 return 语句。
祝你好运!
Ty 所有可爱的输入。
我会尽量把我自己的问题说清楚。
问题:我首先想到我想实现一个php函数或包含在缓冲区中。然而,这不是我想要的,也不是故意的。
解决方案:具有我所需内容的回调函数。通过使用函数 preg_replace_callback(),我可以在缓冲区中找到要替换的文本,然后将其替换为回调(函数)将返回的任何内容。
然后,回调包含必要的文件/.classes ,并使用包含书面内容的函数。
如果您不明白,或者想详细说明/讲述更多关于我的解决方案,请告诉我。