View Single Post

  #3 (permalink)  
Old 12-06-2005
Connector5
 
Posts: n/a
Default Re: Newbie - Transforming string to calculation

Building on Hilarion's response (eval is by far the simplest method) here is
a function that can be used to remove potentially unsavory characters from a
user-supplied formula. This function isn't perfect, meaning errors can
still exist, but you can do your own error catching later:



function is_formula_safe($formula)
{
$valid = explode(' ', chunk_split('0123456789()^.-+*/ ', 1, ' '));

if (str_replace($valid, '', $formula) != $formula)
{
return false;
}
else
{
return true;
}
}



Sample:




if (is_formula_safe($formula))
{
@eval('$result = ' . $formula . ';');
}
else
{
trigger_error("Invalid Formula: $formula", E_USER_WARNING);
$result = 0;
}




"Hilarion" <hilarion@SPAM.op.SMIECI.pl> wrote in message
news:dn48rc$s24$1@news.onet.pl...
> > if I have a string containing a calculation i.e.
> > "5 * 10 - ((5-2)*(10-3))".
> >
> > Is there a simple way for this to be interpreted as values and
> > operators thus providing a result?!?

>
>
> You can use "eval" function:
>
> $expr = '5 * 10 - ((5-2)*(10-3))';
> eval( '$result = ' . $expr . ';' );
> echo $result;
>
> But remember that eval will evaluate any PHP code, so if the
> $expr is comming from external user, than this code allows
> the user to execute any PHP code on the server. In that
> case you should use some VERY GOOD method of expression
> validation to make sure it's only a mathematical expression
> before you evaluate it, or use some parser for mathematical
> expressions instead of the eval.
>
>
> Hilarion



Reply With Quote