Find certain characters in a variable...



I’m working on a registering script, for users to sign up and then login…

I need my script to check if their desired username has any “illegal” characters in it (like $, %, etc)… All I want users to be able to use in their usernames are numbers letter and _ and -… If their username has spaces, or any other characters besides those I want my script to find out.

How would I go about searching a variable and finding those characters?




Here is how I would do it:


<?php $strBadChars=array('*',' ','$','@','&'); $str='example$string'; for($k=0;$k<count($strBadChars);$k++) { if(strpos($str,$strBadChars[$k])!=false) { echo "Bad charactor $strBadChars[$k] found
"; } } ?>



Actually, a white list should be used, rather than a black list, for security reasons. If you use a black list, you can simply forget an important character.


I would suggest looking at regex for your white list. It is fast and powerful (but it does take a bit to learn).


Actually, for simple tasks, simple string functions are much faster than regex. The advantage of regex is that it’s extremely powerful for complex pattern matching.


the only other thing I was going to suggest is the ctype functions.