-
-
Save latik/8bc62f71fd4951afc652d6319e0f17c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function perform($operations, $expr) { | |
| do { | |
| $positions = array_filter(array_map(function ($symbol) use (&$expr) { | |
| return strrpos($expr, $symbol); | |
| }, array_keys($operations)), function ($pos) { | |
| return $pos !== false; | |
| }); | |
| if (empty($positions)) { | |
| break; | |
| } | |
| $last = max($positions); | |
| $expr = $operations[$expr[$last]](calc(substr($expr, 0, $last)), calc(substr($expr, $last + 1))); | |
| } while (true); | |
| return $expr; | |
| } | |
| function calc($expr) { | |
| while (strpos($expr, '(') !== false) { | |
| preg_match('/^(.*)\(([^)]+)\)(.*)$/', $expr, $matches); | |
| $expr = $matches[1] . calc($matches[2]) . $matches[3]; | |
| } | |
| $expr = perform([ | |
| '+' => function ($a, $b) { return $a + $b; }, | |
| '-' => function ($a, $b) { return $a - $b; }, | |
| ], $expr); | |
| $expr = perform([ | |
| '*' => function ($a, $b) { return $a * $b; }, | |
| '/' => function ($a, $b) { return $a / $b; }, | |
| ], $expr); | |
| return floatval(trim((string)$expr)); | |
| } | |
| echo calc('100-(4+4) * (2*(3 + 2))+2*10 / 5'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment