How can PHP developers ensure the security of their applications when using the eval() function for mathematical evaluations?

When using the eval() function for mathematical evaluations in PHP, developers should sanitize user input to prevent potential code injection attacks. One way to do this is by using regular expressions to ensure that only valid mathematical expressions are evaluated.

$user_input = $_POST['math_expression'];
$pattern = '/^[0-9\+\-\*\/\(\) ]+$/'; // Allow only numbers, arithmetic operators, and parentheses
if (preg_match($pattern, $user_input)) {
    $result = eval("return $user_input;");
    echo "Result: $result";
} else {
    echo "Invalid input";
}