fork(1) download
  1. <?php
  2.  
  3. function calculate($expression) {
  4. $chars = preg_split('//u', $expression);
  5. $operators = array('+', '-', '*', '=', '/');
  6. $result = 0;
  7. $lastOperator = '+';
  8. $input = '';
  9. foreach ($chars as $char) {
  10. if (is_numeric($char) or (($char == '.') && (mb_substr_count($input, '.') == 0))) {
  11. $input .= $char;
  12. } elseif (in_array($char, $operators)){
  13. switch ($lastOperator) {
  14. case '+':
  15. $result += floatval($input);
  16. break;
  17. case '-':
  18. $result -= floatval($input);
  19. break;
  20. case '*':
  21. $result *= floatval($input);
  22. break;
  23. case '/':
  24. $result /= floatval($input);
  25. break;
  26. }
  27. if ($char == '=') {
  28. return $result;
  29. }
  30. $input = '';
  31. $lastOperator = $char;
  32. }
  33. }
  34. }
  35.  
  36. echo calculate('25.5 + 35.24.25 =');
  37. ?>
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
60.7425