如何在双引号字符串中写入变量以被 eval() 视为变量

问题描述 投票:0回答:4

这是一段代码,我不明白为什么 PHP 代码的输出是:

This is a $string with my $name in it. This is a cup with my coffee in it.

我的代码:

<?php
$string = 'cup';
$name = 'coffee';

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

// will not echo the value of the strings variable because there in ' '
echo $str. "\n";

// this function is like writing the php code outside of it
// it gets a string with php statments (;) 
// because the code is written in a string
// if it is written it double quotes you have to escape $ and " 
// and if it is written in single quotes you have to escape '

eval("\$str = \"$str\";");

//it is not like this, why?????
//eval('$str = "$str";');

// and not like this, why???????
//$str = "$str" ;

echo $str. "\n";
?>

为什么这段代码中的语句:

eval('$str = "$str";');
或语句:
$str = "$str";
与语句:
eval("\$str = \"$str\";");
没有做同样的事情?

php eval quotes
4个回答
2
投票

双引号字符串计算其中的所有变量。单引号字符串则不然。

现在发表此声明

eval("\$str = \"$str\";");

first

\$str
-> $ 被转义,所以它是一个文字,而不是
$str
变量

第二个

$str
-> $ 没有转义,整个字符串都用双引号括起来,所以这会变成

$str = "This is a $string with my $name in it."

现在这个 PHP 代码被计算,它将右侧的字符串分配给左侧的变量。因此

$str
变成了
This is a cup with my coffee in it

应避免评估。


0
投票
//it is not like this, why?????
//eval('$str = "$str";');

因为输入字符串可能包含单引号,所以不能使用它们来开始和结束字符串。

// and not like this, why???????
//$str = "$str" ;

因为你要计算一个字符串,而上面没有字符串。

我不明白这个例子的意义,只是使用双引号:

<?php
$string = 'cup';
$name = 'coffee';

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

echo $str. "\n";
?>

0
投票

在第一个评估语句中:

eval("\$str = \"$str\";");

由于第二个 $ 没有转义,并且您在整个参数中使用双引号,因此第二个 $str 的值被传递给 eval,并且 eval 的参数变为:

eval("\$str = \"This is a $string with my $name in it.\";");

当评估时,变成:

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

它指定“这是一个杯子,里面有我的咖啡。”至 $str.

在第二次评估中:

eval('$str = "$str";');

评估的陈述是:

$str = "$str";

这与你的第三个陈述相同。执行该语句时,会将非字符串转换为字符串。在这种情况下,$str已经是一个字符串,所以这条语句对$str的值没有影响。

希望这有帮助。 :)


0
投票

为什么在这种情况下需要

eval

单引号内的变量不会被解释,而是放在双引号下。

$str = "This is a $string with my $name in it."; //<--- Replaced single quotes to double quotes.

其次..如果你真的担心逃脱,为什么不使用

HEREDOC
语法

<?php
$string = 'cup';
$name = 'coffee';

$cont=<<<ANYCONTENT
This is a $string with my $name in it. This text can contain single quotes like this ' and also double quotes " too.

ANYCONTENT;

echo $cont;

输出:

This is a cup with my coffee in it. This text can contain single quotes like this ' and also double quotes " too. 
© www.soinside.com 2019 - 2024. All rights reserved.