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

When using eval() in PHP to execute user input as code, it is essential to validate and sanitize the input to prevent potential security vulnerabilities such as code injection attacks. Some best practices for validating user input before using eval() include checking the input against a whitelist of allowed characters or functions, using regular expressions to ensure the input matches the expected format, and filtering out any potentially harmful code.

$user_input = $_POST['user_input'];

// Validate user input before using eval()
if (preg_match('/^[a-zA-Z0-9\s\(\)\.\+\-\*\/%]*$/', $user_input)) {
    // Execute user input with eval() only if it passes validation
    eval($user_input);
} else {
    // Handle invalid input
    echo "Invalid input. Please try again.";
}