2

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?

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
Max
  • 1,341
  • 3
  • 20
  • 39

6 Answers6

3

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.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • Here any way for make regex which only work with math functions and operations? Like: +; -; /; *; sqrt; pow; cos; sin; etc? – Max Mar 12 '12 at 08:16
  • How come you are discouraging the use of eval and giving the same solution? – Starx Mar 12 '12 at 08:37
2

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);
Community
  • 1
  • 1
Starx
  • 77,474
  • 47
  • 185
  • 261
  • Good idea! But need to correct regex a little bit. Cause in math available also cos, sin, pow, etc. – Max Mar 12 '12 at 13:01
1

You could use the eval function:

$result = eval($exr); // show: 4
JMax
  • 26,109
  • 12
  • 69
  • 88
  • Thanks a lot. I can't understand how "googling" with that question?! Bad English :) – Max Mar 12 '12 at 08:07
  • You could try [this query](https://www.google.com/search?q=calculate+math+operation+in+PHP) or see Salman comment's on the accepted answer :) – JMax Mar 12 '12 at 09:06
1

Try:

$exr = "2+3/1.5";
echo eval("return $exr;"); //shows 4
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

You could use eval.

$result = eval($exr);
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
0

The easiest way would be to just run it through eval(), but that is very insecure. For security I'd recommend to filter certain characters, like a-z and special chars like ";:'.

Daniel
  • 3,726
  • 4
  • 26
  • 49