Page 1 of 1

[solved]how to check for banned characters

Posted: Fri Jan 30, 2004 5:24 pm
by vigge89
For my registration page, i don't want the user to be able to use 'bad' characters, ie, only [a-z], [A-Z], [0-9], [_], [-] should be allowed.
But how could i check if there are any 'banned' characters in the requested username?

Posted: Fri Jan 30, 2004 5:54 pm
by pickle
You could use regular expressions. Someone who knows about them should be able to pop one out really quick. I am not one of those people so I would use PHP's string functions. Break the username down character by character and compare that character against legal characters. Dirty I know, but it works.

Posted: Fri Jan 30, 2004 11:40 pm
by McGruff
Native ctype fns are another nice option - not always enabled though.

Posted: Fri Jan 30, 2004 11:56 pm
by markl999
Maybe something like:

Code: Select all

if(preg_match('/([^a-z0-9_-])/i', $username)){
  echo 'Invalid Name';
} else {
  echo 'Valid Name';
}
..but my regex is a but rusty so i'm not 100% that catches everything, but tests seem to go ok :o

Posted: Sat Jan 31, 2004 2:57 am
by vigge89
i'll try that out :D
at first, if I wouldn't have created this topic, I would go for the big boss,
str_replace :P

Posted: Sat Jan 31, 2004 3:20 am
by timvw
So looking for a preg_match with this will do: /[^\w]/

The \w matches any word character, a-zA-Z0-9_

Posted: Sat Jan 31, 2004 3:58 am
by vigge89
great, it works, but why does it return false if the given string matches the pattern?
thats kinda strange :?
anyway, Thanks!

Posted: Sat Jan 31, 2004 5:07 am
by timvw
Thats because of the ^ in front.

Normally, preg_match on /[a]/ would return true of there was an 'a' in the string
the [^a] returns true if there is a character different from 'a' in it.

Posted: Sat Jan 31, 2004 7:57 am
by vigge89
ah, ok.
I know nothing about RegExp, but could someone give me a tutorial or anything about it?
it seems to be so hard :?