No need for regex
For simple operations like validating a username, there is no need to use regex. Instead, use PHP’s built in functions from the Ctype-library.
$testcase = 'AbCd1zyZ9')
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.";
}
…check for digits with ctype_digit
$testcase = "12345";
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.";
}
…or look for visible characters with ctype_graph
$testcase = "asdf\n\r\t";
if (ctype_graph($testcase)) {
echo "The string consists of all (visibly) printable characters.";
} else {
echo "Contains invisible characters.";
}
// RESULT: Contains invisible characters.