What are the best practices for validating user input before executing it with eval() in PHP?

When using eval() in PHP to execute user input, it is crucial to validate the input to prevent potential security vulnerabilities such as code injection attacks. One way to do this is by using regular expressions to ensure the input contains only allowed characters or patterns. Additionally, you can sanitize the input by removing any potentially harmful characters or code snippets before passing it to eval(). It is also recommended to limit the scope of variables accessible to the eval() function to prevent unintended consequences.

$user_input = $_POST['user_input'];

// Validate user input using regular expression
if (preg_match('/^[a-zA-Z0-9\s\+\-\*\/\(\)]+$/', $user_input)) {
    // Sanitize user input by removing potentially harmful characters
    $safe_input = preg_replace('/[^\w\s\+\-\*\/\(\)]/', '', $user_input);

    // Execute the sanitized input using eval()
    eval("\$result = $safe_input;");
    
    // Output the result
    echo "Result: " . $result;
} else {
    echo "Invalid input. Please provide a valid mathematical expression.";
}