fork(1) download
  1. <?php
  2.  
  3.  
  4. $input = '125.34+100*3/2=';
  5.  
  6. $number = 0;
  7. $result = 0;
  8. $op = '';
  9.  
  10. // Находит числа любой длины, в том числе дроби или знаки арифметических операций
  11. if (preg_match_all('/\d+\.?\d*|[\+\-\*\/\=]/', $input, $numbersAndOperations)) {
  12.  
  13. foreach ($numbersAndOperations[0] as $chars) {
  14.  
  15. if ($chars == '-' or $chars == '+' or $chars == '*' or $chars == '/' or $chars == '=') {
  16.  
  17. $op = $chars;
  18. if (!$result) {
  19. $result = $number;
  20. }
  21. $number = 0;
  22.  
  23. } else {
  24.  
  25. // Определяет переменную с десятичной дробью и задает ей тип double, остальным integer
  26. $number = (preg_match('/\d+\.\d+/', $chars)) ? floatval($chars) : intval($chars);
  27.  
  28. switch ($op) {
  29. case '-':
  30. $result -= $number;
  31. break;
  32. case '+':
  33. $result += $number;
  34. break;
  35. case '*':
  36. $result *= $number;
  37. break;
  38. case '/':
  39. $result /= $number;
  40. break;
  41. }
  42.  
  43. }
  44.  
  45. if ($op == '=') {
  46. echo round($result, 2);
  47. exit();
  48. }
  49.  
  50. }
  51.  
  52. }
  53.  
  54. echo "Что-то пошло не так... Выражение пустое или с опечаткой, попробуйте снова.";
Success #stdin #stdout 0.02s 23792KB
stdin
Standard input is empty
stdout
338.01