Pars
Pars

Reputation: 5262

How to check string length in regex

I am new to Regular Expression and tried to write a line of code to match

  1. strings should NOT start with digits. ( OK )
  2. strings should have only alpha, num, dash and underscore in it. ( OK )
  3. strings length should be between 5 and 25 ( FAIL )

rule 1 and 2 works correctly but rule 3 doesn't.

any help to fix it?

This is my code :

$arr = [
    '-foobar',
    'foobar',
    '32-xx',
    'xx23',
    'A2l',
    '2aAA',
    '_a2d',
    '-A22',
    '-34x',
    '2--a',
    'a--a-'

];

foreach( $arr as $a ){
    echo check( $a );
}

function check($string){
    if (preg_match("/^[a-zA-Z]+([a-zA-Z0-9_-]?){5,25}$/", $string)) {
        return "$string ---------------> match was found.<br />";
    } else {
        return "$string ---------------> match was not found.<br />";
    }

}

Upvotes: 1

Views: 5939

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213193

You don't need quantifier + on the first character class. That is just supposed to check the first digit. Then afterwards, you don't need ? quantifier on the 2nd character class. And the range should be {4,24} instead of {3,25}. Also, you can remove the unnecessary capture group from there.

So, modify your regex to:

/^[a-zA-Z][a-zA-Z0-9_-]{4,24}$/

Upvotes: 5

Related Questions