What are best practices for distinguishing between different patterns, such as usernames and email addresses, when using regular expressions in PHP?

When using regular expressions in PHP to distinguish between different patterns like usernames and email addresses, it is important to carefully define the patterns for each and use appropriate regex syntax to match them accurately. For example, usernames may have restrictions on characters allowed, while email addresses must follow a specific format with an "@" symbol and a domain extension. By creating separate regex patterns for each type of data and using functions like preg_match to validate them, you can ensure that the input meets the required criteria.

$username_pattern = '/^[a-zA-Z0-9_]{3,20}$/'; // Pattern for usernames (3-20 characters, alphanumeric and underscore only)
$email_pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'; // Pattern for email addresses

$username = "john_doe123";
$email = "john.doe@example.com";

if (preg_match($username_pattern, $username)) {
    echo "Valid username: $username";
} else {
    echo "Invalid username";
}

if (preg_match($email_pattern, $email)) {
    echo "Valid email address: $email";
} else {
    echo "Invalid email address";
}