If you must use eval , there is code on the eval docs page that allows you to filter math formulas. However, like the others, and the PHP docs page, they said it was not recommended to use eval unless there was another alternative.
<?php $test = '2+3*pi'; // Remove whitespaces $test = preg_replace('/\s+/', '', $test); $number = '(?:\d+(?:[,.]\d+)?|pi|Ο)'; // What is a number $functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions $operators = '[+\/*\^%-]'; // Allowed math operators $regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns if (preg_match($regexp, $q)) { $test = preg_replace('!pi|Ο!', 'pi()', $test); // Replace pi with pi function eval('$result = '.$test.';'); } else { $result = false; } ?>
source share