PHP——表达式求值 发表于 2019-04-29 | 分类于 PHP | 评论数: | 阅读次数: 表达式求值设置一个操作数栈,设置一个操作符栈分析字符串,操作数和操作符分别入栈,如果当前操作符优先级高于栈尾操作符优先级,则先计算栈尾操作符,再把当前操作符号入栈最后把两个栈依次出栈 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120class StrToValue{ private static $operatorLevel = [ '**' => 0, '++' => 1, '--' => 1, '~' => 1, '*' => 2, '/' => 2, '%' => 2, '+' => 3, '-' => 3, '<<' => 4, '>>' => 4, '&' => 5, '^' => 6, '|' => 7, '=' => 8, '+=' => 8, '-=' => 8, '*=' => 8, '**=' => 8, '/=' => 8, '.=' => 8, '%=' => 8, '&=' => 8, '|=' => 8, '^=' => 8, '<<=' => 8, '>>=' => 8, ]; private static $full = [ '~', '*', '/', '%', '+', '-', ]; private static $nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; /** * @param $str * @return array * @throws Exception */ public static function calculate($str) { $len = strlen($str); $numStack = $operatorStack = []; $num = 0; $operator = ''; $isNum = $isOperator = false; $operators = array_keys(self::$operatorLevel); // 分析字符串入栈 for ($i = 0; $i < $len; $i++) { if ($str[$i] === ' ') { continue; } if (in_array($str[$i], self::$nums, true)) { if ($isNum) { $num .= $str[$i]; } else { $num = $str[$i]; if (count($operatorStack) > 0) { $op = array_pop($operatorStack); if (self::$operatorLevel[$op] > self::$operatorLevel[$operator]) { $operatorStack[] = $op; $operatorStack[] = $operator; } else if (count($numStack) > 0) { $right = array_pop($numStack); $left = array_pop($numStack); $aaa = 'return ' . ($left ?? '') . $op . $right . ';'; $numStack[] = eval($aaa); $operatorStack[] = $operator; } } else if ($isOperator !== false) { $operatorStack[] = $operator; } } $isNum = true; $isOperator = false; } else if (in_array($str[$i], $operators, true)) { if ($isOperator) { $operator .= $str[$i]; } else { $operator = $str[$i]; if ($isNum === false) { $numStack[] = !in_array($operator, self::$full, true) ? '' : 0; } else { $numStack[] = $num; } } $isNum = false; $isOperator = true; } else { throw new Exception($str . '包含无效的字符' . $str[$i]); } } if ($isNum) { $numStack[] = $num; } if ($isOperator) { $operatorStack[] = $operator; } // 计算结果(出栈) while (!empty($operatorStack)) { $right = array_pop($numStack); $left = array_pop($numStack); $op = array_pop($operatorStack); $numStack[] = eval('return ' . $left . $op . $right . ';'); } return $numStack[0]; }} 文章不错,你都不请我喝杯茶,就是说你呀! 打赏 微信支付 支付宝