我将我的页面内容保存在数据库中,并希望在字符串中执行任何PHP代码。所以,如果我的字符串是:在字符串中执行PHP代码
<h1>Welcome</h1><?php echo $motto?><br/>
我只是想执行echo $motto
。使用eval()将尝试执行<h1>Welcome</h1>
。
任何方式来做到这一点?
我将我的页面内容保存在数据库中,并希望在字符串中执行任何PHP代码。所以,如果我的字符串是:在字符串中执行PHP代码
<h1>Welcome</h1><?php echo $motto?><br/>
我只是想执行echo $motto
。使用eval()将尝试执行<h1>Welcome</h1>
。
任何方式来做到这一点?
Needles说你应该尽快找到另一种解决方案。在此期间,你可以使用eval这样的代码:
$str = '<h1>Welcome</h1><?php echo $motto?><br/>'; // Your DB content
eval("?> $str <?php ");
演示:http://codepad.org/ao2PPHN7
我不能强调足够:EVAL是危险的,而应用程序代码不应该在数据库中。尝试模板解析器,如Smarty,Dwoo或我的最爱:Twig。
...或简单的'eval(“?> $ str”);'你只需跳出PHP块。 –
你真的不应该这样做,但是,如果你绝对要,你可以使用这个类做:
class PhpStringParser
{
protected $variables;
public function __construct($variables = array())
{
$this->variables = $variables;
}
protected function eval_block($matches)
{
if(is_array($this->variables) && count($this->variables))
{
foreach($this->variables as $var_name => $var_value)
{
$$var_name = $var_value;
}
}
$eval_end = '';
if($matches[1] == '<?=' || $matches[1] == '<?php=')
{
if($matches[2][count($matches[2]-1)] !== ';')
{
$eval_end = ';';
}
}
$return_block = '';
eval('$return_block = ' . $matches[2] . $eval_end);
return $return_block;
}
public function parse($string)
{
return preg_replace_callback('/(\<\?=|\<\?php=|\<\?php)(.*?)\?\>/', array(&$this, 'eval_block'), $string);
}
}
这样称呼它:
$p = new PhpStringParser();
echo $p->parse($string);
将主体保存在数据库中的原因是,客户端可以在我制作的自定义Windows程序中对其进行编辑。我试图以不同的方式进行设置,但同时该网站需要像这样上网。 – bmandesign
与ob_start(); eval(“?> $ str”); $ result = ob_get_clean();'相比,上面有什么好处? – goat
要使用内使用可变呼应字符串:
echo "<h1>Welcome</h1>$motto<br/>"
甚至:
echo sprintf('<h1>Welcome</h1>%s<br/>', $motto)
这里是一个演示http://codepad.org/f6aALD6w
是不断呈现和逻辑独立。必须这样做才能表明您可能想要重新考虑您的设计选择。 – dm03514
对于您构建网站的方式,我现在可以告诉您这会导致问题。以下是我的建议:使用Smarty或类似软件来分离模板和代码。 – Hassan
这看起来像你已经做出了一个非常糟糕的设计决定。 – PeeHaa