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];
- function walk(&$match) {
- $tokens = array();
- while($match) {
- $token = array_shift($match);
- if($token === ')') return $tokens;
- if($token === '(') $token = walk($match);
- array_push($tokens, $token);
- }
- return $match ? walk($match) : $tokens;
- }
- return walk($match);
- }
- 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; }
- );
- $left = array_shift($math);
- $op = array_shift($math);
- $right = array_shift($math);
- $value = $funcs[$op](
- is_array($left) ? resolve($left) : $left,
- is_array($right) ? resolve($right) : $right
- );
- if(!$math) return $value;
- array_unshift($math, $value);
- return resolve($math);
- }
- header('content-type: text/plain');
- $math = tokenize('10 + (11 - (14 / 5)) * 10');
- print_r($math);
- echo resolve($math);
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement