0

Possible Duplicate:
how to evaluate formula passed as string in php?

I have a string like "10*0.1+800" I would like to get the actual answer of the this string in numeric instead of the string value.

I have tried floatval php function but had no luck. Any idea?

Community
  • 1
  • 1
Roshan Wijesena
  • 3,106
  • 8
  • 38
  • 57

3 Answers3

3

You would have to "evaluate" the string using the eval function of PHP:

eval('return ' . $string . ';');

But i would really only do this, if you can trust the string. Because what you are doing here is indeed executing PHP code. It's a possible security hole, if you can't trust the string.

The other possible option would be to use a parser. I am sure, there are already any libraries for this task available.

aurora
  • 9,607
  • 7
  • 36
  • 54
  • 1
    "But i would really only do this, if you can trust the string" - I can't imagine a situation where you would want to eval an arbitrary string, even if you think you can trust it, there may always be a bug that allows insertion of random strings. – fresskoma Nov 15 '11 at 11:50
  • 2
    @x3ro: but than again: you can have bugs everywhere and "stop programming" is not really an option, either ... isn't it? – aurora Nov 15 '11 at 11:53
  • No, but you shouldn't use eval if it is not absolutely necessary, and there are plenty of math expression parsers out there that don't use eval, are there not? – fresskoma Nov 15 '11 at 11:54
  • @x3ro: yes, and i mentioned this, too. but sometimes a real parser is just overkill ... if you can trust the string ;-). – aurora Nov 15 '11 at 11:55
  • @harald: I strongly disagree. Especially given the fact that you don't have to write the parser yourself, there is no upside in using `eval` (except for performance, but then again, you're coding in PHP) and the security risk it introduces is just not proportional to any benefit you might have. The problem is that, by suggesting `eval` here, newbie programmers reading this question will probably adopt the use of eval without reflecting, which I think is really, really bad. – fresskoma Nov 15 '11 at 12:00
  • 1
    @x3o: that's the reason why i wrote about the possible security hole in the answer. in my opinion a newbie programmer should make his own mind about what could be a possible security hole. and imo writing safe applications starts at some other points like trusting / validating data coming into your program from whatever source ... but this is no course about secure programming -- imo. – aurora Nov 15 '11 at 12:13
1

You could try :

$string = "10*0.1+800";
$result = eval("return "+$string);

but beware of the security risks of using eval !

Molochdaa
  • 2,158
  • 1
  • 17
  • 23
0

You can simply use the eval function of php which will evaluate the string.

$str = "10*0.1+800"
eval('return ' . $str. ';');
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137