如何解释php代码的字符串


How to interpret a string for php code?

我有这个:

this string might contain `<?php echo $var; ?>` php code

如果在一个文件中,它将只是一个include/require命令。但这一次eval不起作用。该怎么办?

eval()的文档说:

eval -将字符串作为PHP代码求值

下面还写着:

代码不能用PHP的开始和结束标签来包装,…通过使用适当的PHP标签,仍然可以离开并重新进入PHP模式。

?>放在你的字符串前面,它将成为有效的PHP代码(空代码),后面跟着一些文本,直接发送到输出和更多的PHP代码片段,正确地包含在PHP标签中。

这将做你想做的:

$var = "Hello World!";
$string = 'this string might contain `<?php echo $var; ?>` php code';
//extract command
preg_match('/<'?php(.{1,}?)'?>/',$string,$match);
//print_r($match);
//execute command
eval($match[1]);