I have following code:
<?php
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = preg_replace("/[^0-9\(\)\+\-\*\/\.]/", "", $mathString);
return eval("return $mathString;");
}
$string1 = " (1 + 1) *3+ (2 + 2)";
echo calculate_string($string1);
$string2 = " (1 + 1) *3+* (2 + 2)";
echo calculate_string($string2);
?>
function calculate_string() must calculate math expression given in string as a param. First call on string1 work good.
But, how I can detect if math. string have math. error in syntax like in seconda call,
and return some value depends of error type, or simple return nothing(better solution)?
So, problem is parse_error in second call when math expression contain errors in syntax.
Please help.
Ok, so you’d like to sport something like
*3+*in:Well you can do this in many ways, by checking string yourself for some common errors or by checking
eval()‘s return value (docs):