How can regular expressions be used effectively in PHP to parse and evaluate mathematical expressions?
Regular expressions can be used effectively in PHP to parse and evaluate mathematical expressions by breaking down the expression into its individual components (operands and operators) and then evaluating them accordingly. One approach is to use regular expressions to tokenize the expression, convert it into Reverse Polish Notation (RPN), and then evaluate the RPN expression using a stack-based algorithm.
```php
<?php
function evaluateMathExpression($expression) {
$pattern = '/(\d+|\+|\-|\*|\/|\(|\))/';
preg_match_all($pattern, $expression, $matches);
$tokens = $matches[0];
$output = [];
$stack = [];
$precedence = [
'+' => 1,
'-' => 1,
'*' => 2,
'/' => 2
];
foreach ($tokens as $token) {
if (is_numeric($token)) {
$output[] = $token;
} elseif ($token == '(') {
array_push($stack, $token);
} elseif ($token == ')') {
while (($op = array_pop($stack)) != '(') {
$output[] = $op;
}
} else {
while (!empty($stack) && $precedence[end($stack)] >= $precedence[$token]) {
$output[] = array_pop($stack);
}
array_push($stack, $token);
}
}
while (!empty($stack)) {
$output[] = array_pop($stack);
}
$result = [];
foreach ($output as $token) {
if (is_numeric($token)) {
array_push($result, $token);
} else {
$b = array_pop($result);
$a = array_pop($result);
switch ($token) {
case '+':
array_push($result, $a + $b);
break;
case '-':
array_push($result, $a - $b);
break;
case '*':
array_push($result, $a * $b);
break;
case '/':
array_push($result, $a / $b);
break;
}
}
}
return $result[0];
}
$expression = "3 + 4 * (2 - 1)";
$result = evaluateMathExpression($expression);
echo $result