Home >Backend Development >PHP Tutorial >How Can I Safely Evaluate Mathematical Formulas Passed as Strings in PHP?
Problem:
I'm trying to figure out the proper and safer way to execute mathematical operation passed as string. In my scenario it is values fetched from image EXIF data.
After little research I found two way of doing it.
function calculator1($str){ eval("$str = $str;"); return $str; }
function calculator2($str){ $fn = create_function("", "return ({$str});" ); return $fn(); };
Both examples require string cleanup to avoid malicious code execution. Is there any other or shorter way of doing so?
Answer:
function calculator3($str){ $m = new EvalMath; return $m->evaluate($str); }
This method uses the EvalMath class, which is specifically designed to safely evaluate mathematical expressions from untrusted sources. It provides robust error checking and only evaluates a limited set of functions.
Here's an example of how to use it:
$str = '2+2'; $result = calculator3($str); echo $result; // Output: 4
The above is the detailed content of How Can I Safely Evaluate Mathematical Formulas Passed as Strings in PHP?. For more information, please follow other related articles on the PHP Chinese website!