Re: Evaluating math without eval()
| From: | Jason Norwood-Young | Date: | Thu, 10 Apr 2008 13:42:12 +0000 |
| Subject: | Re: Evaluating math without eval() | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-272831@lists.php.net to get a copy of this message | ||
On Thu, 2008-04-10 at 13:15 +0100, Richard Heyes wrote:
> > First post to this list! I'm trying to figure out how to evaluate a
> > string with a mathematical expression and get a result, but without
> > using eval() as I'm accepting user input into the string. I don't just
> > want addition, subtraction, multiplication and division - I'd like to
> > take advantage of other functions like ceil, floor etc.
In reply to my own question, I came up with the following function based
on a comment on php.net
(http://www.php.net/manual/en/function.eval.php#71045). I had a look at
the array returned by get_defined_functions() and the maths functions
seem mostly to be grouped (with the exception of the random number
stuff). It works on my installation but there's nothing in the
documentation about get_defined_functions() returning in a particular
order - it would be safer to list each math function but I'm lazy.
protected function safe_eval($s) {
$funcs=get_defined_functions();
$funcs=$funcs["internal"];
$funcs=array_slice($funcs,array_search("abs",
$funcs),array_search("rad2deg",$funcs)-array_search("abs",$funcs));
$sfuncs="(".implode(")(",$funcs).")";
$s=preg_replace('
([^+\-*=/\(\)\d\^<>&|\.'.$sfuncs.']*)','',$s);
if (empty($s)) {
return 0;
} else {
try {
eval("\$s=$s;");
return $s;
} catch(Exception $e) {
return 0;
}
}
}