How can a custom parser be implemented in PHP to handle complex arithmetic expressions effectively?

To handle complex arithmetic expressions effectively in PHP, a custom parser can be implemented. This parser should be able to tokenize the input expression, parse it according to the rules of arithmetic operations, and evaluate the expression to produce the correct result. By implementing a custom parser, you can have more control over how the expressions are processed and handle complex operations efficiently.

<?php

function custom_parser($expression) {
    $tokens = preg_split('/(\+|\-|\*|\/)/', $expression, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    
    $result = 0;
    $operator = '+';
    
    foreach ($tokens as $token) {
        if ($token == '+' || $token == '-' || $token == '*' || $token == '/') {
            $operator = $token;
        } else {
            switch ($operator) {
                case '+':
                    $result += $token;
                    break;
                case '-':
                    $result -= $token;
                    break;
                case '*':
                    $result *= $token;
                    break;
                case '/':
                    $result /= $token;
                    break;
            }
        }
    }
    
    return $result;
}

// Example usage
$expression = "3 + 4 * 2 - 6 / 3";
$result = custom_parser($expression);
echo "Result: " . $result;

?>