0

我将 HTML 内容存储在具有文本数据类型的 MySQL 字段中,并且我使用 ckeditor 作为 WYSIWYG 编辑器来创建存储在 MySQL 中的 HTML。我正在寻找一种方法让用户放置某种我可以查找并替换为调用包含文件的字符串。例如:

// This string contains the text pulled from mysql
$pageContent = "<p>This page contains a calendar of events</p> {{calendar}} <p>Choose a date or scroll through days to view events.</p>";

// Function needed that changes {{calendar}} to bring in my script calendar.php like include('calendar.php');
// Note that in this example I want to call my script that does the calendar stuff, but maybe I have a script to do a photo gallery which could be {{photogallery}}, or news {{news}}, or whatever...

// Print the $pageContent including the calendar.php contents here
print $pageContent;
4

1 回答 1

0

这里有一个小东西,它将获取您的文本(在本例中为$pageContent)和一组参数(即 array('calendar' => 'calendar.php'))并包含必要的文件。它目前未经测试,但应该让您朝着正确的方向前进。

function parseTemplate($templateText, $params)
{
    foreach ($params as $key => $value)
    {
        ob_start();
        include($value);
        $includeContents = ob_get_contents();
        ob_end_clean();
        $templateText = str_replace('{{'.$key.'}}', $includeContents, $templateText);
    }
    return $templateText;
}

在您的情况下,用法如下:

// This string contains the text pulled from mysql
$pageContent = "<p>This page contains a calendar of events</p> {{calendar}} <p>Choose a date or scroll through days to view events.</p>";

$params = array('calendar' => 'calendar.php');
$pageContent = parseTemplate($pageContent, $params);

// print the $pageContent including the calendar.php contents here
print $pageContent;

您也可以使用相同的想法来简单地替换文本而不是包含文件:

function parseTemplateText($templateText, $params)
{
    foreach ($params as $key => $value)
    {
        $templateText = str_replace('{{'.$key.'}}', $value, $templateText);
    }
    return $templateText;
}
于 2012-11-14T15:03:35.333 回答