title: php regex syntax to whitelist alphanumeric
body: <p>I am trying to use preg_match to whitelist usernames with alphanumeric characters and screen out those with special characters but code is not acting as I'd like</p>
  
  <p>Here is is:</p>
  
  <pre><code>PHP
  
  $username = "karl#";
  if (!preg_match("#^[a-zA-Z0-9]+$#", $username))
  {
  $msg = "You may not use special characters in your username";
  }
  else {
  $msg = "ok";
  }
  </code></pre>
  
  <p>returns "ok".  In other words, it is letting karl# get through.  I would like it to return error message.</p>
  
  <p>Am I misusing preg-match or what am I doing wrong?  Thank you for any suggestions.</p>
  
  <p>Edit: The code above does work.  Error was because in original version I was not hard coding the username but rather getting it as post and there was a problem with post.  I accepted the answer below using ^\w+$ as it allows for underscore and is more concise.  Thanks also for all the fine points on regex contained in comments.</p>