class MATH_REPLACE{
function MATH_REPLACE(){
}
function replace($InputString){
$Matchs = preg_match_all("/\(+[0-9+\s+\-.*\/()%]+\)/", $InputString, $mMatchs);
for ($i=0;$i<$Matchs; $i++){
$Formula = str_replace(" ", "", $mMatchs[0][$i]);
$Formula = preg_replace("/([+-])([0-9]+)(%)/", "*(1\$1.\$2)", $Formula);
$Formula = preg_replace("/([0-9]+)(%)/",".\$1",$Formula);
eval("\$Result=" . $Formula . ";");
$Pos = strpos($InputString, $mMatchs[0][$i]);
$InputString = substr_replace($InputString, $Result, $Pos, strlen($mMatchs[0][$i]));
}
return $InputString;
}
}
//The math expression must to be between '(' and ')'
$Porcent = 10;
$Cadena = "The result of [[40+15]*2] + $Porcent% IS (((40+15)*2)+ $Porcent%)";
$ObjSalida = new MATH_REPLACE;
$Salida = $ObjSalida->replace($Cadena);
echo "<BR>".$Salida;