在不使用eval的情况下将字符串计算为PHP代码

时间:2013-11-24 07:32:29

标签: php 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()

?>

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

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

3 个答案:

答案 0 :(得分:2)

您可以像这样布局代码:

$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); 

根据个人风格和不同,有不同的选择。偏好。

答案 1 :(得分:1)

你真正想要的是为$ str使用双引号,以便可以进行变量替换。

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

答案 2 :(得分:1)

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

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

echo $str;