Checking a Username for valid characters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cent
Forum Newbie
Posts: 16
Joined: Wed Nov 16, 2005 2:23 pm

Checking a Username for valid characters

Post by cent »

Hi All,

Trying to figure out something that I have no real knowledge of... preg_match. I search around the boards here and other PHP programming sites and put together the closest thing I could find that suits my needs. BUT... it doesn't work right.

Basically, the username passed to the function should only contain A-Z, a-z, 0-9, the underscore "_" character and no spaces. Anything else should return false.

Code: Select all

function checkUsername($uname)
{
	return preg_match("/[A-z]+[0-9]+[_]/",$uname);
}

Am I missing something here or did I format it incorrectly? As I mentioned, preg_matches and ereg calls are new to me.

Thanks in advance,

Best,
Cent
allanonschick
Forum Newbie
Posts: 2
Joined: Sun Nov 20, 2005 11:42 pm
Location: Los Angeles, California
Contact:

Post by allanonschick »

Code: Select all

function checkUsername($uname) 
{ 
    return preg_match('/^[A-Za-z0-9_]+$/', $uname);
Can you try this instead?
cent
Forum Newbie
Posts: 16
Joined: Wed Nov 16, 2005 2:23 pm

Post by cent »

That did the job... thanks for the help.

Best,
Cent.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

I'm by no means a regex guru, but I think this pattern would work too:

Code: Select all

/^(\w)*$/
\w is a meta character meaning all word characters (a-z, A-Z, 0-9, and _).
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply