What are the best practices for validating and escaping user input in PHP before using it in functions like preg_match?

When dealing with user input in PHP, it is crucial to validate and escape the data to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One common method is to use functions like `filter_input()` to sanitize input data before using it in functions like `preg_match()`. By validating and escaping user input, you can ensure that your application is secure and protected from malicious attacks.

$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

if ($user_input !== false) {
    if (preg_match('/^[a-zA-Z0-9_]+$/', $user_input)) {
        // Input is valid, proceed with using it in your application
    } else {
        // Input contains invalid characters
        echo "Invalid input";
    }
} else {
    // Input is empty or not provided
    echo "Input is required";
}