need a regular expression for check numbers&letters&_ only

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
mostafa272
Forum Newbie
Posts: 3
Joined: Tue Apr 17, 2012 1:21 am

need a regular expression for check numbers&letters&_ only

Post by mostafa272 »

Hi

I check username in my login page with following code that it allow to have a username with numbers and letters and _ only!

Code: Select all

$user=preg_replace("([^a-z0-9_]*)",'',$user);
now,I want to forbid users to have a username with other characters in my register page and I want to check it with preg_match function,but I don't know what regular expression is suitable for it!please help me!

thanks
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: need a regular expression for check numbers&letters&_ on

Post by requinix »

Code: Select all

/[^a-z0-9_]/
Use that with preg_match. If it matches then the username is invalid.
Last edited by requinix on Tue Apr 17, 2012 11:52 am, edited 1 time in total.
mostafa272
Forum Newbie
Posts: 3
Joined: Tue Apr 17, 2012 1:21 am

Re: need a regular expression for check numbers&letters&_ on

Post by mostafa272 »

it is not that expression i need it.I want an expression that find every character in a string except small letters,numbers,and _.
because username must has a small letters,numbers,_. and other things will be replaced with above code.
users can select a username with small letters,numbers,_.i want to find other characters in usernames and send error message to users.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: need a regular expression for check numbers&letters&_ on

Post by requinix »

There was a typo: missed out on the ^.

So you actually want to know every single invalid character in the username? Same expression still, just give it to preg_match_all().
Or if you only care about knowing whether the username is invalid at all - whether it contains anything that's not a letter, number, or underscore - then it's still that expression.
Post Reply