I leave here a way without using eval()
, for this already has an answer that was made longer ago whose @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);
DEMONSTRATION
Source: Excellent response withdrawn from here
This is it: do the mathematical calculation from the already composed string: "3 + 2 = 5"
– Rafael