What are best practices for validating input using regular expressions in PHP?

When validating input using regular expressions in PHP, it is important to ensure that the regular expression pattern matches the expected format of the input data. This can help prevent unexpected or malicious input from being processed by your application. It is also a good practice to sanitize the input data before using it in any database queries or output to prevent SQL injection attacks.

// Example of validating an email address using a regular expression
$email = "test@example.com";

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