# 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)
{
continue;
}

if (\$val)
{
switch (\$operators[\$i])
{
case '+':
break;

case '-':
break;

case '*':
break;

case '/':
break;

case '^':
break;

case '%':
}

\$i++;
}
}

}

``````

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

Couldnt you something like

``````

``````

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

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/