[英]process embedded variable within a string using PHP
How do I process a variable that was embedded within a string? 如何处理嵌入在字符串中的变量? The string came from a database, so here is an example:
该字符串来自数据库,因此这里是一个示例:
1: $b='World!';
2: $a='Hello $b'; #note, I used single quote purposely to emulate the string was originally from the database (I know the different of using ' or ").
3: eval($c=$a.";"); #I know this would not work, but trying to do $c="Hello $b";
#With line 3 PHP code, I am trying get the outcome of $c='Hello World!';
If you want to eval the line of code $c='Hello World';
如果要评估代码行
$c='Hello World';
you should have a string that when echo
ed you will get exactly that: $c="Hello $b";
您应该有一个字符串,当
echo
ed时,您将得到准确的字符串: $c="Hello $b";
. 。
So - for start, your $c
variable should be inside a string (and not as a variable); 因此-首先,您的
$c
变量应位于字符串内(而不是作为变量);
'$c'
Next - the =
sign should be inside a string (and not as part of the php code, otherwise the preprocessor will try to assign the value on the right to the variable on the left. 接下来-
=
号应放在字符串内(而不是php代码的一部分,否则预处理器将尝试将右侧的值分配给左侧的变量。
How about this one: 这个怎么样:
$new_str = '$c=' . $a . ';';
echo $new_str;
Now you can see that the value inside $new_str
is actually: 现在您可以看到
$new_str
中的值实际上是:
$c=Hello $b;
Which is not a valid php code (because you don't have Hello in PHP. What you actually want is to have the Hello $b part inside a double-quote: 这不是有效的php代码(因为PHP中没有Hello。您真正想要的是将Hello $ b部分放在双引号中:
$new_str = '$c="' . $a . '";';
And only now you can eval this. 而且只有现在,您才能对此进行评估。
So your final code should look like: 因此,您的最终代码应如下所示:
$b='World!';
$a='Hello $b';
eval('$c="' . $a . '";');
echo $c; // Hello World!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.