PHP: Stripping special characters out of input

Associate
Joined
29 Dec 2004
Posts
2,252
I have a form with an input "username". I would like to strip special characters out of the username before it is inserted into my DB. I currently have:

Code:
$username = preg_replace('#\s+#s', ' ', $username);

Which removes multiple whitespaces and converts them into one, but how can i modify it to remove special characters aswell? When i say special characters i mean stuff like:

-_!"£$%^&*()#~`¬¦€

I ONLY want a person to be able to have a-z, A-Z, and 0-9 in their username...help?! How do i change that line to incorporate removing the special characters? I dont want hypens or underscores either!
 
Berserker said:
Code:
$username = preg_replace('/[^a-zA-Z0-9]/', '', $username);
Doubtless there's a more 'elegant' solution. :)

Thanks...will that sort my whitespaces out aswell? If not is there any way to "add" the whitespaces bit in there too, or will the above not allow whitespaces anyway because they arent a-z/A-Z or 0-9?

Really appreciate your help :)
 
Back
Top Bottom