-1

我有一个从数据库调用内容的变量,示例如下

$content = '<div><h1>content here</h1>
<img src = 'image.jpg' /><br />

[code]echo 'welcome';[/code]

<h2>some content here</h2>
<p> some large content here</p>

[code]echo 'Click Here';[/code]

Thank you.';

echo 'headers here' .$content . 'footers here';

如何为 [code] 和 [/code] 标签之间的内容执行 PHP?剩余的文本将写为 html execpt 中使用的代码[code] some php code [/code] tags

4

1 回答 1

1

如果这是针对您网站的模板类型系统,我建议采用不同的路线。

首先,您的上述代码会发生变化,以便您的代码之间的部分如下所示:

[code]{{msg}}}[/code]

现在,如果您愿意,您仍然可以将您的东西作为 php 代码存储在数据库中,但是在将其放入数据库之前对其进行评估更有意义,但我强烈建议不要使用查找/替换系统。

现在,您会想要一个可以执行以下操作的函数:

function output_template( $name, $data ) {
    $template_string = get_template_from_db( $name );
    for( $data as $k )
    {
        $template_string = str_replace( $k, $data[$k], $template_string );
    }
    return $template_string;
}

然后你可以回显这个函数的返回值。如果您认为需要使用 eval,请重新考虑您在做什么,尤其是对于看似模板系统的东西。

于 2012-07-20T15:20:31.477 回答