如何在特定标记之间替换代码并对其应用php-eval


How to replace code between the specific tags and apply php eval on it

我有一个变量,它调用数据库中的内容,示例在下面

$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]中使用,一些php代码[/code]标签

如果这是针对您的网站的模板化类型的系统,我建议走另一条路。

首先,你上面的代码会发生变化,所以你代码之间的部分看起来像:

[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,请重新思考您正在做什么,尤其是对于看起来像模板系统的系统。