I would like to create a preg_match
function to validate my username, my code below not working perfectly, especially on Must contain at least 4 letter lowercase
rules and number not more than 4 character and place behind letter
if (preg_match('/^[a-z0-9]{4,12}/', $_POST['username']))
Here are my username rules that I want to work :
Thank you for any help you can offer.
You match these criteria, maybe this will be an option:
^[a-z](?=(?:[a-z]*\d){0,4}(?![a-z]*\d))(?=[a-z\d]{3,11}$)[a-z\d]+$
This will match
^
[a-z]
(?=
which asserts that what follows is(?:
[a-z]*\d
){0,4}
(?!
Which asserts that what follows is not[a-z\d]*
)
)
(?=
which asserts that what follows is(?=[a-z\d]{3,11}$)
)
[a-z\d]+$
Regex: ^[a-z]{4,8}[0-9]{0,4}$|^[a-z]{4,12}$
Details:
^
Asserts position at start of a line$
Asserts position at the end of a line[]
Match a single character present in the list{n,m}
Matches between n
and m
times|
OrPHP code:
$strings=['testtesttest', 'testtesttestr', 'test12345', 'testtest1234', 'testte123432'];
foreach($strings as $string){
$match = preg_match('~^[a-z]{4,8}[0-9]{0,4}$|^[a-z]{4,12}$~', $string);
echo ($string . ' => len: (' . strlen($string) . ') ' .($match ? 'true' : 'false')."
");
}
Output:
testtesttest => len: (12) true
testtesttestr => len: (13) false
test12345 => len: (9) false
testtest1234 => len: (12) true
testte123432 => len: (12) false