The Context
I'm in need of a bit of code that takes a very simple math string and runs PHP's eval()
function. For example ...
$math = '25 * (233 - 1.5)';
echo eval("return $math;"); // returns 5787.5
However eval()
is quite dangerous in the wrong hands, so the variable must be scrubbed. For the above, for example, a simple preg_replace would be ...
$math = '25 * (233 - 1.5)';
$replace = '/[^0-9\(\)\.\,\+\-\*\/\s]/';
$math = preg_replace($replace, '', $math);
echo eval("return $math;"); // returns 5787.5
... which ensures $math
only contains valid characters ... .,+-*/
, spaces and numbers, and no malicious code.
The Question
I want to allow a few very specific words (PHP math functions), such as pow
, pi
, min
, max
, etc.
What's the cleanest way to validate both characters and words in regex?
So if given this string ...
pow(25,2) / pi(); hack the pentagon;
... how would I remove everything that wasn't in the $replace
regex, but preserve the words pow
and pi
?