What are some alternatives to using eval() in PHP for evaluating mathematical expressions stored in a variable?

Using eval() in PHP to evaluate mathematical expressions stored in a variable can be risky as it can execute arbitrary code and pose security vulnerabilities. An alternative approach is to use built-in functions like eval() or create a custom parser to evaluate the mathematical expressions safely.

// Custom function to evaluate mathematical expressions
function evaluateMathExpression($expression) {
    $result = null;
    $expression = preg_replace('/[^0-9+\-\/\*\(\)\.]/', '', $expression); // Sanitize input
    if (is_numeric($expression)) {
        $result = $expression;
    } else {
        eval('$result = ' . $expression . ';');
    }
    return $result;
}

// Example usage
$mathExpression = "2 + 3 * (5 - 1)";
echo evaluateMathExpression($mathExpression); // Output: 14