在字符串中执行 PHP 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10866301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute PHP code in a string
提问by bmandesign
I have my page contents saved in a database and would like to execute any php code in the string. So if my string was:
我将页面内容保存在数据库中,并希望执行字符串中的任何 php 代码。所以如果我的字符串是:
<h1>Welcome</h1><?php echo $motto?><br/>
I only want to execute echo $motto. Using eval() will try to execute <h1>Welcome</h1>.
我只想执行echo $motto. 使用 eval() 将尝试执行<h1>Welcome</h1>.
Any way to do this?
有没有办法做到这一点?
回答by Wesley Murch
Needless to say you should find another solution ASAP. In the meantime you can eval the code like this:
不用说,您应该尽快找到另一个解决方案。同时,您可以像这样评估代码:
$str = '<h1>Welcome</h1><?php echo $motto?><br/>'; // Your DB content
eval("?> $str <?php ");
Demo: http://codepad.org/ao2PPHN7
演示:http: //codepad.org/ao2PPHN7
I can't stress that enough: eval is dangerous, and application code shouldn't be in the database. Try a template parser like Smarty, Dwoo, or my favorite: Twig.
我再怎么强调都不为过:eval 是危险的,应用程序代码不应该在数据库中。尝试使用Smarty、Dwoo或我最喜欢的模板解析器:Twig。
回答by Jeroen
You reallyshouldn't do this, but if you absolutely have to, you can do it by using this class:
你真的不应该这样做,但如果你绝对必须这样做,你可以通过使用这个类来做到:
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);
}
}
Call it like this:
像这样调用它:
$p = new PhpStringParser();
echo $p->parse($string);
Source: http://www.php.net/manual/en/function.eval.php#108091
回答by PassTeT
To echo string with a variable inside use:
使用内部变量回显字符串:
echo "<h1>Welcome</h1>$motto<br/>"
Or even:
甚至:
echo sprintf('<h1>Welcome</h1>%s<br/>', $motto)
Here is a demo http://codepad.org/f6aALD6w

