Despite PHP lacking a built-in function for evaluating arithmetic expressions from strings, there are alternative solutions that eliminate the need for manually separating operators and operands.
infix to postfix(RPN) parser and RPN Solver
The EOS class provides an infix parser to convert an expression like "2-1" to postfix notation (RPN), which is then evaluated by the RPN solver. The following code demonstrates:
require_once "eos.class.php"; $eq = new eqEOS(); $result = $eq->solveIF("2-1"); echo $result; // Prints 1
Other Options
Recommendation
While eval remains an option for expression evaluation, it's strongly discouraged due to security risks. The EOS class or other alternatives offer secure and efficient methods for solving arithmetic expressions in PHP.
The above is the detailed content of How Can I Safely Evaluate String Arithmetic Expressions in PHP?. For more information, please follow other related articles on the PHP Chinese website!