In the context of PHP, how can one ensure that a user-inputted mathematical expression is safe to evaluate using eval?

When evaluating user-inputted mathematical expressions using eval in PHP, it's important to sanitize the input to prevent potential code injection attacks. One way to ensure safety is to use a regular expression to validate the input and only allow mathematical operators and numbers. This can help prevent malicious code from being executed during the evaluation process.

$user_input = $_POST['math_expression'];

// Validate user input to ensure it only contains numbers and mathematical operators
if (preg_match('/^[0-9\+\-\*\/\(\) ]+$/', $user_input)) {
    $result = eval("return $user_input;");
    echo "Result: $result";
} else {
    echo "Invalid input. Please enter a valid mathematical expression.";
}