在不使用eval的情况下,将字符串求值为PHP代码


Evaluate a string as PHP code without using eval

了解如何避免eval,如何在不使用eval的情况下将字符串求值为PHP代码?例如,考虑以下代码:

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.'; 
$str = "'"$str'""; // Now I have a string with double quotes around it. 
// how to get the contents of $str evaluated without using eval()
?>

我可以像so-eval("echo $str;");一样使用eval来获得所需的结果,但eval正是我想要避免的。

您可能会将此视为删除双引号的问题。但这与此无关。正如@AmalMurali所指出的,我在这里所问的是how to get the contents of $str evaluated without using eval()

您可以这样布局代码:

$string = 'cup';
$name = 'coffee';
$str = 'This is a ' . $string . ' with my ' . $name . ' in it.'; 

或者像这样,使用sprintf,这是我个人最喜欢的处理这种情况的方法:

$string = 'cup';
$name = 'coffee';
$str = sprintf('This is a %s with my %s in it.', $string, $name); 

根据个人风格有不同的选择;偏爱

这里真正想要的是对$str使用双引号,这样就可以进行变量替换。

另请参阅文档:http://www.php.net/manual/it/language.types.string.php#language.types.string.syntax.double

为什么添加双引号,然后删除它们?对于一个简单的字符串变量包含,你只需要使用像这样的双引号

$string = 'cup';
$name = 'coffee';
$str = "This is a $string with my $name in it."; 
echo $str;