String expression in integer result
Question by Maxim Droy
After a lot of operations I’ve got some like:
$exr = "2+3/1.5";
How I can get result of this expression? Like this:
$result = (floatval)$exr; // show: 4
Of course it doesn’t work. I’ve got only 2, first symbol.
Any easy way to solve this?
Answer by Salman A
You can use the PHP eval
function like this:
$exr = '2+3/1.5';
eval('$result = ' . $exr . ';');
var_dump($result);
// float(4)
Read this note carefully:
Caution: The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
Answer by Starx
Eval is EVIL
I dont know why every answer here is telling you to do this? But avoid using this.
Here is very good function that can do the same without the eval() Source
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = ereg_replace ('[^0-9+-*/() ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
Use it as
$exr = '2+3/1.5';
echo calculate_string($exr);