Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function tokenize($expr) {
- preg_match_all('/(?:-|)\d+|\+|-|\*|\/|\(|\)/', $expr, $match);
- $match = $match[0];
- $tokens = array();
- $stack = array();
- $precedence = array('+' => 1, '-' => 1, '*' => 2, '/' => 2);
- while($match) {
- $token = array_shift($match);
- if(is_numeric($token)) {
- array_push($tokens, $token);
- }
- else {
- if($token === ')') {
- while($stack && end($stack) !== '(') {
- array_push($tokens, array_pop($stack));
- }
- array_pop($stack);
- continue;
- }
- while($token !== '(' && ($stack && end($stack) !== '(') && $precedence[$token] < $precedence[end($stack)]) {
- array_push($tokens, array_pop($stack));
- }
- array_push($stack, $token);
- }
- }
- return array_merge($tokens, array_reverse($stack));
- }
- function resolve($math) {
- $funcs = array(
- '+' => function ($left, $right) { return $left + $right; },
- '-' => function ($left, $right) { return $left - $right; },
- '/' => function ($left, $right) { return $left / $right; },
- '*' => function ($left, $right) { return $left * $right; }
- );
- $stack = array();
- while(count($math) > 1) {
- $token = array_shift($math);
- if(!is_numeric($token)) {
- $token = $funcs[$token](array_shift($math), array_shift($math));
- }
- array_push($stack, $token);
- }
- return $stack[0];
- }
- header('content-type: text/plain');
- $math = tokenize('2*3+4*(5 - 6)');
- echo implode(' ', $math) . PHP_EOL;
- echo resolve($math);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement