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?