We have a system that has to perform calculations that user input provides.
The easiest way I have found to do one of those calculations is eval — trying to figure out a parser for:
(3 + 6 ) / 2 + 27 * 5 / 2
Just seems difficult. If anyone has a solution to this — I would be happy to hear it.
Assuming you are going with EVAL (I know its the dreaded function) it would be a major insecurity to allow them to type whatever they want in that box.
So, I pose the question, if I did a regex removing everything besides numbers, standard operators (+ – / *) and parentheses, something like
$equation = preg_replace( '/[^0-9+-\/*()]/', '', $input_equation );
$result = eval( $equation );
Is there any harm that could possibly happen to a system?
I recently coded a PEDMAS compliant interpreter that uses BCMath functions:
It supports the following operators:
^(pow)*/%(modulus)+-=,==,<,<=,>,>=(comparison)And you call it like this:
I did this so I had an easy way to perform arbitrary length calculations but, in your case, you might as well just strip all whitespace and validate the characters using the following regular expression: