if (ctype_alnum($username)) {
  // Username is valid
}
https://www.php.net/manual/tr/function.ctype-alnum.php