I need to do form calculations with php, for example, I will have a field in which I will put 2 + 9 (4 * 8) / 6 and it will return the result, but I have no idea how to do it. how I need it:
I need to do form calculations with php, for example, I will have a field in which I will put 2 + 9 (4 * 8) / 6 and it will return the result, but I have no idea how to do it. how I need it:
I leave here a way without using eval()
, so you already have a response that was made the longest ago @Bacco put the link on top of the question:
function callback1($m) {return c($m[1]);}
function callback2($n,$m) {
$o=$m[0];
$m[0]=' ';
return $o=='+' ? $n+$m : ($o=='-' ? $n-$m : ($o=='*' ? $n*$m : $n/$m));
}
function c($s){
while ($s != ($t = preg_replace_callback('/\(([^()]*)\)/','callback1',$s))) $s=$t;
preg_match_all('![-+/*].*?[\d.]+!', "+$s", $m);
return array_reduce($m[0], 'callback2');
}
$str = '(3 + 2) * 5';
echo c($str);
Source: Great answer taken from here