Find certain characters in a variable...


#1

Hey,

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?

Thanks,

Nick


#2

Here is how I would do it:

[code]

<?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
"; } } ?>

[/code][/code]


#3

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.


#4

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


#5

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.


#6

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