Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Simple regular expressions to match length?

I'm creating a registration system that needs to check the name/pass etc. with REGEX (and prefer to), what I've got so far is:

//Check so numbers aren't first, such as 00foobar
preg_match('/^(?!\d)[a-z0-9]+$/iD',$usrname);
//Just simple check
preg_match('/^[a-zA-Z0-9]+$/',$psword);

But I have to do stupid things in IF statements like:

if strlen($psword) > 30 || if (strlen($psword) < 4) ....

How would I impliment the length checking in my two original regular expression statements? This would make me so happy..

like image 522
oni-kun Avatar asked Feb 07 '10 01:02

oni-kun


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

How do I match a character in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_replace() in PHP – this function is used to perform a pattern match on a string and then replace the match with the specified text.

How do you match a regular expression?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

same but using the \w and \d for word and digits, but you might want also to include basic symbols like %!?/ ... etc...

preg_match('/^[\w\d]{4,30}$/',$psword);

the {n,v} would validate for minimum n and maximum v elements before.

like A{2,3} would validate for AA and AAA. you can take a look there for more references

On the same fashion if you want only to set the minimum of patern {n,} would do it. For example:

preg_match('/^[\w\d]{4,}$/',$psword);
like image 171
RageZ Avatar answered Oct 06 '22 00:10

RageZ


I think this should do the trick:

preg_match('/^[a-zA-Z0-9]{4,30}$/',$psword);

like image 22
dchakarov Avatar answered Oct 05 '22 23:10

dchakarov