I would like to know if there was a secure way to evaluate mathematics like
2+2
10000+12000
10000-20
2 + 2
40 - 20 + 23 - 12
Without having to use eval() because the input can come from any users. The things I’d need to implement are only additions and subtractions of whole numbers.
Is there any snippets that already exists for that, or any PHP functions I haven’t come across?
I would question using
eval, considering the variety of mathematic functions available in PHP. You’ve said you only want to do simple math — the only reason to useevalis to perform more complex operations, or to accept the equations whole-cloth from the user.If you just want to add or subtract, sanitize the input with
intvaland go to town:Try it: http://codepad.org/LSUDUw1M
This works because
intvalignores anything non-numeric.If you are indeed getting the whole equation from user input (ie
100 - 20), you can usepreg_replaceto remove anything except the allowed operators and numbers:Try it: http://codepad.org/tnISDPJ3
Here, we’re using the regex
/[^0-9+-]/, which matches anything NOT 0-9 OR + OR – and replaces it with an empty string.If you want to get more in to depth with allowed equations, taken straight from the
evalmanual page:Documentation
preg_replace– http://php.net/manual/en/function.preg-replace.phpintval– http://php.net/manual/en/function.intval.phpeval– http://php.net/manual/en/function.eval.php