[Phpwm] Fnuction to calculate a formula

Richard Harrison php at rjharrison.org
Mon Dec 3 20:14:21 GMT 2007


You could use eval()... but it's potentially a security issue / Bad Thing.

Depending on how complex your expressions are you could parse them for 
the operator, and use a callback:-


<?php

$formula = '2+2';
$callbacks = array('+' => '_addition');


if(preg_match('/^(.*?)([\+])(.*?)$/', $formula, $matches)){
   
    $a            = $matches[1];
    $operator = $matches[2];
    $b            = $matches[3];

    $callback = $callbacks[$operator];
    $result     = $callback($a, $b);  

    echo $formula, ' = ', $result;
}

function _addition($a, $b){
    return $a+$b;
}
?>


I think using regular expressions is pretty crude (and limited) but it 
gets the job done. The 'right' way to do it is properly parse the 
formula for tokens (using some sort of finite-state machine 
implementation?). There's a PEAR package that might be a good place to 
start (http://pear.php.net/package/FSM).

Regards,

Richard.

Colin Taylor wrote:
> Hello,
> I am on the hunt for a PHP 5 function that will calculate a given formula.
> 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