How to calculate strings with PHP

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:     
Posted by admin in featured, PHP/mySQL on 27th Apr, 2010
tabs-top

16 Comments »

  1. uyab

    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.

  2. holodoc

    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 :P

  3. Hidden things

    Thank you so much, i was very blank before i got this great solution from you.

  4. luckgo

    very good!
    thank u!

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

  6. Great..

    Thanks

  7. [...] 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 [...]

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

  9. Alberto

    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'

  10. Meinereiner

    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.

  11. Ronna Pailo

    Thank you so much, very useful

  12. Khen Solomon Lethil

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

  13. very useful, thankÅ›

  14. mihaicux

    brilliant

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

  16. Maria

    Garcias..!!

Leave a comment

SEO Blogs - BlogCatalog Blog Directory