What are the common pitfalls when using preg_match in PHP for username validation?

Common pitfalls when using preg_match for username validation in PHP include not properly defining the regex pattern to match the allowed characters, not accounting for the minimum and maximum length of the username, and not handling special characters or whitespace. To solve this, make sure to define a regex pattern that includes the allowed characters, set the minimum and maximum length constraints, and consider any special characters that should be allowed.

$username = "username123";

if (preg_match('/^[a-zA-Z0-9]{5,20}$/', $username)) {
    echo "Username is valid.";
} else {
    echo "Invalid username. Username should be between 5 to 20 characters long and can only contain letters and numbers.";
}