1

What is the best way to filter username in PHP :-

I have everything that I need working, but I would like to verify that a username entered during the registration only contains alphanumeric characters. So how could I take a variable, say $username, and ensure that it contained only alphanumeric characters?

John smith
  • 87
  • 1
  • 8
  • Could you add some code to your question? – andrewsi Jul 22 '13 at 18:37
  • Your probably looking for a regular expression like the one described in http://stackoverflow.com/questions/336210/regular-expression-for-alphanumeric-and-underscores. – Steven V Jul 22 '13 at 18:37
  • This regex expression may help: http://stackoverflow.com/questions/5199133/function-to-return-only-alpha-numeric-characters-from-string – Peter Jul 22 '13 at 18:39

2 Answers2

9
<?
if (ctype_alnum($user)) {
   //YAY THE STRING IS ALPHANUMERIC!
}
?>
Kirk Backus
  • 4,776
  • 4
  • 32
  • 52
2

You can use the ctype_alnum function:

if (ctype_alnum($username)) {
    // here, $username is alphanumeric
}
jh314
  • 27,144
  • 16
  • 62
  • 82