What are the best practices for using regular expressions to validate user input in PHP?

When using regular expressions to validate user input in PHP, it is important to define clear and specific patterns to match the expected input. This helps ensure that the input meets the desired format and prevents potential security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, it is recommended to sanitize the input before using regular expressions to further enhance security.

// Example of using regular expressions to validate an email address input
$email = $_POST['email'];

if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    // Valid email address
    echo "Email address is valid";
} else {
    // Invalid email address
    echo "Invalid email address";
}