What are some common pitfalls when using regular expressions in PHP for validating email addresses and usernames?

One common pitfall when using regular expressions in PHP for validating email addresses and usernames is not accounting for all possible valid formats. It's important to consider edge cases such as special characters or multiple dots in email addresses. To solve this, you can use more comprehensive regular expressions that cover a wider range of valid patterns.

// Validate email address with a more comprehensive regular expression
$email = "test@example.com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email address";
} else {
    echo "Valid email address";
}