Reputation: 5262
I am new to Regular Expression and tried to write a line of code to match
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
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