Evaluate math from a string?

I have a basic function that evaluates a string as a mathmatical expression and then returns the answer to it.

It only does basic arithmetic, but incorrectly, because I don’t know how to implement parenthesis as to enable order of operations.

Here is the function:

function arithmetic($expression)
{
	$temp_op = preg_replace('([^\\+\\-*\\/%\\^])', ' ', trim($expression));
	$temp_op = explode(' ', trim($temp_op));
	
	foreach ($temp_op as $key => $val)
	{
		if ($val)
			$operators[] = $val;
	}
	
	$numbers = preg_replace('([^0-9])', ' ', trim($expression));
	$numbers = explode(' ', $numbers);
	
	$i = 0;
	
	foreach ($numbers AS $key => $val)
	{
		if ($key == 0)
		{
			$answer = $val;
			continue;
		}
	
		if ($val)
		{
			switch ($operators[$i])
			{
				case '+':
					$answer += $val;
					break;
					
				case '-':
					$answer -= $val;
					break;
					
				case '*':
					$answer *= $val;
					break;
					
				case '/':
					$answer /= $val;
					break;
					
				case '^':
					$answer ^= $val;
					break;
					
				case '%':
					$answer %= $val;
			}
			
			$i++;
		}
	}
	
	return $answer;
}

Any suggestions on the problem, or the function in general? :wink:

Couldnt you something like


eval('$answer ='.$expression.';');

That way you just use the full power of the PHP math engine. :slight_smile:

Eval is one option. If you wanted to do it without eval and build a properly working parser, you won’t get far with regular expressions.
You would need to store each number and operator in a tree. The operators are always the root of the tree. Then you need to traverse through the tree using inorder.

Here is some theory and also Pascal code:
http://www.mactech.com/articles/mactech/Vol.07/07.05/MathParser/

Also google for [google]Math parser[/google] to get more information.

BTW, this isn’t a very easy task.

that link there was very interesting