Hi,

Can someone lead me in the right direction on how to write a preg_match.

I have username and password in the DB.

And the username should be case sensitive, accordingly to whatever is in the db.
And it should only be able to contain numbers and letters.

I have this, but I havent used preg_match before, sp I am a little confused on how the syntax works and where to put what i want.

if(preg_match('/^[A-Z\'.-]{2-20}$/i',$_POST['username'])){
 $username = trim($_POST['username']);
 $username = mysqli_real_escape_string($connection, $username);	
}

Hope somene can explain me the way this chinese is to be translated :-)

Recommended Answers

All 4 Replies

Regular expressions can be tough to understand.

Taking the example you've posted, there are a couple of mistakes:

if(preg_match("/^[a-z\d'\.\-]{2,20}$/i", $_POST['username'])) {
    // ...
}

Looking at the expression, you'll see that I have enclosed it in double quotes rather than single. This is to avoid issues with the single quote you wish to allow.

The square brackets have been used to enclose all available characters. Within this, I have added a-z, which is obvious. This could also be A-Z, given the inclusion of the i, case insensitive, flag.

The . character has a special meaning in regular expressions, in that it matches any character. To use this as a normal period character, you need to escape it first.

Likewise, the - character is used to specify a range in regular expressions, e.g. 0-3 or a-z. This again is escaped.

The {2,20} indicates that the value must be between 2 and 20 characters in length. You could have this as an open ended range at either end by omitting a value. E.g. {2,} would mean at least 2 characters, {,20} would mean no more than 20.

Hope this helps.
R.

commented: another lesson for me +13
commented: Nice lecture, huh... :-) Also appreciate to me too. +6

If you really want to get good with regular expressions I can recommend this book: Mastering Regular Expressions by Jeffrey E.F. Friedl, published by O'Reilly & Associates. This book is some 300 pages long! It is very detailed and covers almost any flavor of regex you are likely to come across - because sadly, there are lots of variants. But he makes it all very clear and easy to follow imvho.

Likewise, the - character is used to specify a range in regular expressions, e.g. 0-3 or a-z. This again is escaped.

The dash is used for ranges only if it is between two characters. If it is just after [ or before ] you don't need to escape it.

@twiss - Really? I didn't know that, thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.