As an alternative to the regular expression approaches already provided by
others, you could also use ctype_alnum():

if (ctyp_alnum($_POST['username'])) {
   //username contains only letters and numbers
} else {
   //username contains characters other than letters and numbers
} //if-else

Docs: <>

As a bonus, this will likely be quite a bit quicker than the regex-based
approaches. That said, you'd have to be making many calls (e.g., inside a
loop) for the difference to reach the point of being noticeable. For
something like a one-time validation on page-load, use whichever you find
most comfortable.

In your original question, you also mentioned looping through a variable
to check for non-alphanumeric characters. The regex approach or the
approach I outlined above is much better in this case, but as a learning
exercise, you could do the looping like this:

$validCharacters = array('a', 'e', 'i', 'o', 'u');
for ($i = 0; $i < count($_POST['username']); $i++) {
   if (in_array($_POST['username'][$i], $validCharacters)) {
      echo 'Pass!';
  } else {
      echo 'Fail!';
   } //if-else
} //for i

The key thing to note there is that you can treat the string like it's an
array to loop through it. For more information about this, go here:


and search the page for the phrase "String access and modification by


Robert E. Williams, Jr.
Associate Vice President of Software Development
Newtek Businesss Services, Inc. -- The Small Business Authority

Notice: This communication, including attachments, may contain information that 
is confidential. It constitutes non-public information intended to be conveyed 
only to the designated recipient(s). If the reader or recipient of this 
communication is not the intended recipient, an employee or agent of the 
intended recipient who is responsible for delivering it to the intended 
recipient, or if you believe that you have received this communication in 
error, please notify the sender immediately by return e-mail and promptly 
delete this e-mail, including attachments without reading or saving them in any 
manner. The unauthorized use, dissemination, distribution, or reproduction of 
this e-mail, including attachments, is prohibited and may be unlawful. If you 
have received this email in error, please notify us immediately by e-mail or 
telephone and delete the e-mail and the attachments (if any).

PHP General Mailing List (
To unsubscribe, visit:

Reply via email to