Guest User

calcNumbers

a guest
May 30th, 2011
167
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $calc = array(
  2.     '+' => 'bcadd',
  3.     '-' => 'bcsub',
  4.     '*' => 'bcmul'
  5. );
  6. $mathString = '5*19+45-6*7+21';
  7. $numbers = preg_split('/[\+\-*]+/', $mathString);
  8. $operators = preg_split('/[\d]+/', $mathString, -1, PREG_SPLIT_NO_EMPTY);
  9. $numOperators =count($operators);
  10. for ($i = 0; $i< $numOperators; $i++) {
  11.     if ($operators[$i] == '*') {
  12.         $numbers[$i] = call_user_func('bcmul', $numbers[$i], $numbers[$i+1]);
  13.         $numbers[$i+1] = 0;
  14.         $operators[$i] = '+';
  15.     }
  16. }
  17. $sum = $numbers[0];
  18. for ($i = 0; $i< $numOperators; $i++) {
  19.     $sum = call_user_func($calc[$operators[$i]], $sum, $numbers[$i+1]);
  20. }
  21. echo "Result: ".$sum;
RAW Paste Data