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:
$string2 = " (1 + 1) *3+* (2 + 2)";
Well you can do this in many ways, by checking string yourself for some common errors or by checking eval()
's return value (docs):
As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned FALSE and execution of the following code continued normally. It is not possible to catch a parse error in eval() using set_error_handler().