-6

My question is,

How can we separate out digits and operators from a string in PHP?

Eg - What is 2 + 2?

So, how can we take the 2 + 2 out from that string, CALCULATE it, and display the appropriate result?

Thanks.

dgw
  • 13,418
  • 11
  • 56
  • 54
Abhishek
  • 9
  • 2
  • Possible duplicate of: [How to evaluate formula passed as string in PHP?](http://stackoverflow.com/q/1015242/367456) – hakre Sep 25 '13 at 06:01

3 Answers3

2
function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); 

    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
}

$string = " (1 + 1) * (2 + 2)";
echo calculate_string($string);
emilan
  • 12,825
  • 11
  • 32
  • 37
1

Take a look at the evalMath class on PHPClasses, which can handle quite complex formulae.

Alternatively:

$string = '2 + 2';
list($operand1,$operator,$operand2) = sscanf($string,'%d %[+\-*/] %d');
switch($operator) {
    case '+' :
        $result = $operand1 + $operand2;
        break;
    case '-' :
        $result = $operand1 - $operand2;
        break;
    case '*' :
        $result = $operand1 * $operand2;
        break;
    case '/' :
        $result = $operand1 / $operand2;
        break;
}
echo $result;
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

If you want to calculate something that does not take into account grouping operators (such as ( and ) ) or follow the order of operations / operator precedence, this is a fairly straightforward.

If however you do want to take those things into account, then you have to be willing to write a parser for a context free language.

OR, you could search for a library out there that has already been written

Community
  • 1
  • 1
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96