help with preg_match and PHP

Discussion about the creation of websites in general, HTML, PHP, Java.

help with preg_match and PHP

Postby thoriumbr on Wed Aug 24, 2005 2:55 pm

Hi everyone,

I have a problem in a site I am working in... I have to validate the username, because it can be only letters and numbers, started with a letter...
I tried to use preg_match(), but I don't know how to use regular expressions... It is hard to my brain assimilate all that codes, chars and magic things I have to put into my string...
I had read the manual, put can't undestand too much, and the little I undestanded was misunderstanded since not worked...

Any help?
thoriumbr
Contributer
Contributer
 
Posts: 26
Joined: Tue Aug 23, 2005 1:49 pm
Location: Limeira, SP, Brazil

Postby al_tyranny on Thu Aug 25, 2005 4:01 am

Please note that I know no php ... I do know some Google though Wink

Here's a site I found for "php regular expressions":
http://weblogtoolscollection.com/regex/regex.php

If you can use underscores, it would probably be something like:
Code: Select all
preg_match("/[a-z][\w]{3,14}/i", $YOURSTRING);

What that does is looks for a letter (case insensitive because the "i" modifier at the end), followed by 3-14 word characters (letters, numbers, and underscore).

If you do not allow the underscore (and I will be very angry, because I use one =P), you could try:
Code: Select all
preg_match("/[a-z][a-z\d]{3,14}/i", $YOURSTRING);

This does exactly the same, only it looks for a letter or a digit, but not an underscore.

Depending on the length of your username, you might have to change the values inside the braces though, this assumes a 4-15 character username.
mm_freak wrote:Slackware users are dreamers. Sorry to say.
al_tyranny
Phoenix Veteran
Phoenix Veteran
 
Posts: 294
Joined: Tue May 17, 2005 3:18 am
Location: Greater Boston Area

Postby goose on Tue Sep 27, 2005 7:49 pm

Well .. the ad sure does lead you in the right direction.. lol.. (regex buddy!)

Regex buddy is great tool for learning and building regular expression.

There are a number of regular expression websites that can help

http://www.regular-expressions.info/

http://renschler.net/regexbuilder/

KODOS!!
http://kodos.sourceforge.net/comments.html
goose
Contributer
Contributer
 
Posts: 69
Joined: Tue Sep 27, 2005 7:05 pm
Location: United States

Postby mm_freak on Thu Sep 29, 2005 3:00 am

Regex for mixed-case usernames starting with a letter, the first is for unlimited length, the second is with length limited to 14 characters:

Code: Select all
^[A-Za-z][A-Za-z0-9]*$
^[A-Za-z][A-Za-z0-9]{1,13}$


Same as above, but with lowercase only:

Code: Select all
^[a-z][a-z0-9]*$
^[a-z][a-z0-9]{1,13}$
I'm x^10 + x^8 + x^5 + x^4 + x^3 + 1, so don't mess with me!
mm_freak
Moderator
Moderator
 
Posts: 635
Joined: Sun Sep 11, 2005 12:29 pm
Location: Baden-Wuerttemberg (Germany)


Return to General Webmastering

Who is online

Users browsing this forum: No registered users and 1 guest

cron