Page 1 of 1

[Solved]Calculating expression in string

Posted: Fri Aug 05, 2005 6:43 pm
by dzim
Hi.

I have a string:

$cost = '$price/$duration*$fix';

and I need to calculate the cost.
If I use eval() function, it just replaces variables with numbers,
but it does nothing with operators '/' and '*'.
Is there any other way to do this, except parsing it "manualy"?

Thanks.

Posted: Fri Aug 05, 2005 6:53 pm
by s.dot
don't put it in quotes

Code: Select all

$cost = $price/$duration*$fix;
Keep in mind the order of operations will be in effect. Mulitply and divide first, then subtraction and add, then lastly, left to right

so if you want ($price/$duration)*fix or $price/($duration*fix) make sure you specify that with ()'s

Posted: Fri Aug 05, 2005 8:16 pm
by timvw
Assuming you get the string at runtime, so there is no way to get it parsed regularly... But be careful where you get the string from, because there will be a day that people send you 'exec("rm -rf /")'

Code: Select all

$string = '$price/$duration*$fix';
eval('<?php $cost=' . $string . ';?>');

Posted: Sat Aug 06, 2005 3:16 am
by dzim
scrotaye wrote:don't put it in quotes
It's not my decision. :)
I'm getting the string from mySQL.
scrotaye wrote: Keep in mind the order of operations will be in effect. Mulitply and divide first, then subtraction and add, then lastly, left to right
so if you want ($price/$duration)*fix or $price/($duration*fix) make sure you specify that with ()'s

I will, thanks.

Posted: Sat Aug 06, 2005 3:20 am
by dzim
timvw wrote:Assuming you get the string at runtime, so there is no way to get it parsed regularly... But be careful where you get the string from, because there will be a day that people send you 'exec("rm -rf /")'

Code: Select all

$string = '$price/$duration*$fix';
eval('<?php $cost=' . $string . ';?>');
As it says under my name, I'm a newbie. :)
I tried:

Code: Select all

eval ('$cost = $string;');
and it didn't work, of course. :)
Again, for future generations, you should use:

Code: Select all

eval('$cost ='. $string . ';');
Thanks, timvw.