How can regular expressions be used to parse and process mathematical expressions in PHP?

Regular expressions can be used to parse and process mathematical expressions in PHP by defining patterns to match specific components of the expression such as numbers, operators, and parentheses. By using regular expressions, you can extract and manipulate these components to evaluate the mathematical expression.

$expression = "3 + 4 * (2 - 1)";
$pattern = '/(\d+|\+|\-|\*|\/|\(|\))/';
preg_match_all($pattern, $expression, $matches);

$tokens = $matches[0];
foreach ($tokens as $token) {
    echo $token . " ";
}