On 09/22/2011 10:36 PM, Robert Williams wrote: > 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: <http://us3.php.net/manual/en/function.ctype-alnum.php> > > > 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: > > <http://us2.php.net/manual/en/language.types.string.php> > > and search the page for the phrase "String access and modification by > character". > > And if you want to go the loop way, you could use range() to fill values in $validCharacters. $validCharacters = array_merge(range('A', 'Z'), range('a', 'z')); -- Nilesh Govindarajan http://nileshgr.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php