If you want to allow math input and make sure that the input is proper mathematics and not some hacking code, you can try this:
<?php
$test = '2+3*pi';
$test = preg_replace('/\s+/', '', $test);
$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; $functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; $operators = '[+\/*\^%-]'; $regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; if (preg_match($regexp, $q))
{
$test = preg_replace('!pi|π!', 'pi()', $test); eval('$result = '.$test.';');
}
else
{
$result = false;
}
?>
I can't guarantee you absolutely that this will block every possible malicious code nor that it will block malformed code, but that's better than the matheval function below which will allow malformed code like '2+2+' which will throw an error.