How to calculate strings with PHP

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

3 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.

Leave a comment

SEO Blogs - BlogCatalog Blog Directory