Hi all,
Could you help me out here plz?
I want to validate a username with regular expressions, where username can begin with letters or numbers, and it may follow with the only underscore(_) and/or the only dot(.). Finally username should end with letters or numbers.
Ex:
Valid user names:
hello_world
HELLO.World
hello.beautiful_world
Invalid usernames:
hello__world
HELLO..World
hello._beautiful_.world
btw, underscore and dot orders are not important. What i mean is, first may come an underscore, then a dot. Or the other way around.
Could you write the code with preg_match, plz?
Thank you.
a simple regex question
Moderator: General Moderators
Reading your post, it almost sounds like you only want to allow a maximum of one underscore and/or period, am I right?
If not:
Also, there's an regex forum dedicated to questions regarding regular expressions. I suggest you post any future questions of this sort there 
If not:
Code: Select all
if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)?$#i", $username)):
// username is not valid
endif;- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Thanx for your reply!vigge89 wrote:Reading your post, it almost sounds like you only want to allow a maximum of one underscore and/or period, am I right?
If not:Also, there's an regex forum dedicated to questions regarding regular expressions. I suggest you post any future questions of this sort thereCode: Select all
if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)?$#i", $username)): // username is not valid endif;
But I think it is not working properly.
For example, hello.beautiful_world is supposed to be a valid username, but your code says its invalid.
Any other suggestions?
Woops, mistake (switch ? for *):
Code: Select all
if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)*$#i", $username)):
// username is not valid
endif;Watch out for exponential matching. Things can really be sped up by using possessive quantifiers:vigge89 wrote:Code: Select all
if (!preg_match("#^[a-z0-9]+([._][a-z0-9]+)*$#i", $username)): // username is not valid endif;
Code: Select all
#^[a-z0-9]++([._][a-z0-9]++)*$#iJust looked possesive quantifiers up as I've never used it (or seen it) before, cheers for that 