How can special characters, like "#" in a username, be detected and prevented in PHP?

Special characters, like "#" in a username, can be detected and prevented in PHP by using regular expressions to check if the username contains any characters outside of a specified set of allowed characters. By defining a pattern that only allows alphanumeric characters and underscores, you can ensure that special characters like "#" are not included in the username.

$username = "user#123";

if (preg_match('/^[a-zA-Z0-9_]*$/', $username)) {
    echo "Username is valid.";
} else {
    echo "Username contains special characters.";
}