Ever wondering to calculate 2 + 2 ? Sure you have.
But what about your formula comes into a string input ?
So, how to calculate “2 + 2″ or “4 * ( 3 – 5 )” in PHP ?
We’ll have the function calculate_string($mathstring).
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
$string = " (1 + 1) * (2 + 2)";
echo calculate_string($string); // outputs 8
thank you so much, after an hour searching, finally I found this website, calculate formula without eval(), look great. I’ll use your code in my final project.
A very nice trick. Took me a couple of seconds to realize what exactly you are doing but in fact its a very simple yet effective and most importantly eval-less aproach
Thanks for the idea. I will steal it
Thank you so much, i was very blank before i got this great solution from you.