Ever wondering to calculate 2 + 2 ? Sure you have.

But what if your formula comes in 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

Demo:

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.

very good!

thank u!

I dont know but I think that solution is same like eval …

Great..

Thanks

[...] This function is for calculating a given calculation in a string. e.g. (1+1)*(2+2) ‘Borrowed’ from http://www.website55.com/php-mysql/2010/04/how-to-calculate-strings-with-php.html [...]

I agree, there is no difference to using eval. You should no longer use “ereg_replace”, this is discontinued.

It shows me this error

Parse error: syntax error, unexpected ‘<' in /var/local/… : runtime-created function on line 1

on the line that calls create_function.

Could you tell me what can cause that?

$mathString='4+2'

The whole thing breaks as soon as the string doesn’t have the right syntax (eg. 3*(2+2)- ). And as it is the same as eval it’s quiet dangerous.

And ereg is indeed deprecated. But this shouldn’t be a big issue.

Thank you so much, very useful

Thank you and I will use this code. can we also check that the string is calculable or not?

very useful, thankÅ›

brilliant

[...] Here is very good function that can do the same without the eval() Source [...]

Garcias..!!