1
<?php

// expression is in variable
$var = "1+2*3/4"

// and I want it to perform and show but calculated:
echo $var; // excepted: 2.25

?>

所以我在变量中有计算表达式,然后我需要计算。可能吗?

4

2 回答 2

2

The way is to evaluate the expression.

echo eval('echo '.$var.';');

which gave me 2.5 bytheway.. and thats the right answer :)

Please consider that eval(); is dangerous to expose to anyone, and very hard to secure.

"echo 3+4; echo file_get_contents('index.php');"

You eval() this as a submitted string, and i have the sourcecode of your PHP. Incluing possibly your DB password, which i can now freely connect to, and dump on my screen at my whim. I can also put unlink('index.php'); in there, which is just plain destructive.

于 2013-08-28T23:51:25.363 回答
1

There is a function named eval that can deal with this but you should take great precautions when using it:

http://php.net/manual/en/function.eval.php

<?php

$var = eval("echo 1+2*3/4;");
echo $var;
// val is 2.5 (2*3/4 is calculated first, then 1 is added to the result)

$var = eval("echo (1+2)*3/4;"); 
echo $var; // val is 2.25
?>

for an explanation about why parenthesis is needed, see http://en.wikipedia.org/wiki/Order_of_operations

Most importantly you need to make sure that the string you send to eval does not contain anything that it shouldn't

eval is very dangerous to use. You have been warned

于 2013-08-28T23:49:24.747 回答