Creating a Calculator in PHP
Simplifying mathematical expressions entered into an tag in PHP can be challenging, especially when preserving the original notation. While a brute-force approach of replacing strings with calculated values seems viable initially, it becomes inefficient.
Utilizing the Shunting Yard Algorithm
A more effective solution is the Shunting Yard Algorithm. It converts input expressions into Reverse Polish Notation (RPN). RPN simplifies calculations as operands are immediately followed by their operators.
Implementation Example
The following code provides an implementation of the Shunting Yard Algorithm in PHP:
class Expression { protected $tokens; protected $output; // Shunting Yard Algorithm public function shuntingYard($input) { $stack = []; $tokens = $this->tokenize($input); foreach ($tokens as $token) { if (is_numeric($token)) { $this->output[] = $token; } else { switch ($token) { case '(': $stack[] = $token; break; case ')': while ($stack && end($stack) != '(') { $this->output[] = array_pop($stack); } if (!empty($stack)) { array_pop($stack); } break; default: while ($stack && $this->precedence($token) <= $this->precedence(end($stack))) { $this->output[] = array_pop($stack); } $stack[] = $token; break; } } } while (!empty($stack)) { $this->output[] = array_pop($stack); } } // Tokenize the input public function tokenize($input) { preg_match_all('~\d+|~|~U', $input, $tokens); return $tokens[0]; } // Operator precedence public function precedence($operator) { switch ($operator) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 0; } } // Evaluate the RPN expression public function evaluate() { $stack = []; foreach ($this->output as $token) { if (is_numeric($token)) { $stack[] = $token; } else { $operand2 = array_pop($stack); $operand1 = array_pop($stack); switch ($token) { case '+': $result = $operand1 + $operand2; break; case '-': $result = $operand1 - $operand2; break; case '*': $result = $operand1 * $operand2; break; case '/': $result = $operand1 / $operand2; break; } $stack[] = $result; } } return array_pop($stack); } } $expression = new Expression(); $expression->shuntingYard('8*(5+1)'); $result = $expression->evaluate(); echo $result; // Output: 48
This code translates the input into RPN, evaluates the resulting stack, and returns the final result.
The above is the detailed content of How Can the Shunting Yard Algorithm Simplify Mathematical Expression Evaluation in PHP?. For more information, please follow other related articles on the PHP Chinese website!