Evaluating Mathematical Expressions from Strings Using Eval
Issue:
When attempting to evaluate a mathematical expression stored in a string using eval(), a "Parse error" occurs, indicating an unexpected end of input.
Solution:
While it's generally not recommended to use eval() for this purpose due to security concerns, the following code modification resolves the issue:
$ma = "2+10"; $p = eval('return ' . $ma . ';'); print $p;
By explicitly returning the result within an eval() function, the code expects a complete line of code.
Alternative Solution:
A more secure and efficient solution is to use a tokenizer/parser to handle mathematical expressions. Here's a simple regex-based example:
$ma = "2+10"; if (preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $ma, $matches) !== FALSE) { $operator = $matches[2]; switch ($operator) { case '+': $p = $matches[1] + $matches[3]; break; case '-': $p = $matches[1] - $matches[3]; break; case '*': $p = $matches[1] * $matches[3]; break; case '/': $p = $matches[1] / $matches[3]; break; } echo $p; }
The above is the detailed content of How to Safely Evaluate Mathematical Expressions from Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!