[Phpwm] Fnuction to calculate a formula

Elliot Smith elliot at townx.org
Mon Dec 3 20:36:09 GMT 2007


Colin Taylor wrote:
> Hello,
> I am on the hunt for a PHP 5 function that will calculate a given formula.
>   
Providing users aren't supplying the input, eval() seems OK to me. Call 
me crazy if you like.

If they are supplying the input, I think I would screen the formula 
first (e.g. using reg. exp.s) to strip out anything which isn't part of 
the formulas you're expecting ( e.g. only allow digits, +, -, /, *, () 
). The problem with trying to write your own arithmetic parser is that 
you've got to account for a lot of stuff (e.g. operator precedence isn't 
going to be trivial).

Elliot

> For example:
>
> $formula="2+2";
> $result=calculate_formula($formula);
> echo "$formula = $result";
>
> Would reult in:
>
> 2+2 = 4
>
> Anyone got any ideas?
> Cheers,
> Colin
>
> _______________________________________________
> Phpwm mailing list
> Phpwm at mailman.lug.org.uk
> https://mailman.lug.org.uk/mailman/listinfo/phpwm
>   




More information about the Phpwm mailing list