php variable substitution/expansion

We know that a variable will be substituted with its value in a “” delimited string such as:

$var1=”var1″;

echo “this is $var1″;

will print “this is var1″.

This variable expansion only happens when the variable name is not preceded with \. If $var is preceded with \, the \ acts as an escape character, which escapes the following $, making $ an ordinary character, and of course \ itself won’t be in the string. So the following code will print “$var2″:

$var2=”\$var2″;

echo $var2;

But we should notice that the variable substitution is not iterative. So:

$v3=”v3″;
$v2=”\$v3″;
$v1=”$v2″;
echo $v1;

will print “$v3″, i.e., after $v2 is expanded to “$v3″, $v3 won’t be expanded to “v3″ any more. The following code includes a subtle error. Can you find it?

$price=”$123″;

$content=”old price is $321, new price is what?”;

$content=preg_replace(“#(what)#i”,”$price”,$content);

echo $content;

Can you figure out what the output is? Newbies may think it will print “old price is $321, new price is $123?”. Unfortunately, it is not true. The actual output is “old price is $321, new price is 3?”. Why should this happen? We should analysis the execution process of the preg_replace statement. In the first step, variables get expanded, i.e., the preg_replace statement becomes:

$content=preg_replace(“#(what)#i”,”$123″,$content);

Note that when preg_replace is executed in the second step, $12 in the replacement string will be replaced with the captured value in the matching process, in this case, there are only two captured values: $0=what,$1=what, $2-$99 are empty. Because php only supports 100 captured values($0-$99), so $123 is recognized as {$12}3, and {$12} is substituted with the captured value “”(empty string). In the last step, the replacement string “3” is used to replace the the patten and get the final result.

Posted in

Comments are closed, but trackbacks and pingbacks are open.