What are alternative methods to evaluate mathematical expressions in PHP without using eval()?

Using the eval() function in PHP to evaluate mathematical expressions can be risky as it can execute arbitrary code. An alternative method is to use the built-in functions like evalMath() or create a custom parser function to evaluate mathematical expressions in a safer way.

// Using built-in evalMath() function
$math = new EvalMath();
$result = $math->evaluate('2 + 2 * 3');

// Custom parser function
function evaluateMathExpression($expression) {
    $result = null;
    if (preg_match('/^[0-9\+\-\*\/\(\) ]+$/', $expression)) {
        eval('$result = ' . $expression . ';');
    } else {
        $result = "Invalid expression";
    }
    return $result;
}

$result = evaluateMathExpression('2 + 2 * 3');