What are the best practices for validating usernames in PHP to allow a specific set of characters?

When validating usernames in PHP to allow a specific set of characters, it is important to use regular expressions to define the allowed characters and length constraints. This ensures that only valid usernames are accepted and helps prevent any potential security vulnerabilities.

$username = "user123";

// Define the allowed characters using a regular expression
$pattern = '/^[a-zA-Z0-9_]{3,20}$/';

// Validate the username against the defined pattern
if (preg_match($pattern, $username)) {
    echo "Username is valid.";
} else {
    echo "Invalid username. Please use only letters, numbers, and underscores.";
}