0

Looked at 2 other regex related questions and both were vastly beyond what I need help with X'D.

<?php 

$userName = trim($_POST['username']);
if(preg_match("/^[a-zA-Z].*(?(\d)).{8,}$/", $userName)){
    
    echo 'woot!';

I'm not really sure why its failing. I know its checking the first character must be alpha, then go more * but check at the end if its a digit ?(\d)... But why wont it check if the length of my $userName is 8 or more?

if I do

... *(?(\d){8,} 

Its going to look for 8 or more digits as opposed to if the string itself is 8 or more.

User must: start with letter, only end in numbers, and can only contain alphaNumeric, must be at least characters 8 long, and treat lower and uppercase the same. Which is to say I need to add an i at the end of my regex.


As so there is no way to work it into a regex aside form look aheads? ^...$.{8,} wouldn't work?

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Please clearly tell us what the rules are for a username? It is clear that it must start with a letter, and also have a digit at some later point. The rest is not clear. – Tim Biegeleisen May 30 '21 at 05:01
  • User must: start with letter, only end in numbers, and can only contain alphaNumeric, must be atleast characters 8 long, and treat lower and uppercase the same. Which is to say I need to add an i at the end of my regex. – Coding_Noob May 30 '21 at 05:07

2 Answers2

3

User must: start with letter, only end in numbers, and can only contain alphaNumeric, must be at least characters 8 long, and treat lower and uppercase the same.

You may use this simple regex to meet this requirement:

^[A-Za-z][a-zA-Z\d]{6,}\d$

RegEx Details:

  • ^: Start
  • [A-Za-z]: Match an ASCII letter at the start
  • [a-zA-Z\d]{6,}: Match a letter or digit 6 or more times
  • \d: Match a digit before end
  • $: end

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Use the following regex pattern:

^(?=.{8,}$)[A-Z][A-Z0-9]*[0-9]+$

Sample script:

$userName = trim($_POST['username']);
if (preg_match("/^(?=.{8,}$)[A-Z][A-Z0-9]*[0-9]+$/i", $userName)) {
    echo "MATCH";
}

Of note, the regex pattern uses (?=.{8,}$) at the start of the pattern. This is a positive lookahead, which asserts that the match is at least 8 characters.

If you don't want to use a lookahead, you may just explicitly check the username length using strlen():

$userName = trim($_POST['username']);
if (preg_match("/^[A-Z][A-Z0-9]*[0-9]+$/i", $userName) &&
    strlen($userName) >= 8) {
    echo "MATCH";
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360