Domanda

I have this regex and I'm using PHP preg_match to filter the username. I want to create conditions:

  • Minmal 3 character and must begin with a-zA-Z
  • Cannot end with underscore
  • if string contains underscore "_" the next underscore should be a-zA-Z0-9 (ex. a_3, hello_w) basically this will prevent username more than one underscore such as a _ _ h. but repeated underscore such as a_h_t_e is not a problem.
  • Underscore is optional.
  • Username can only contains a-zA-Z0-9 and underscore

This is my code:

/^(?=.{3})[A-Za-z][A-Za-z0-9](?:_[A-Za-z0-9]+)[A-Za-z0-9]$/

I tried a few other ways too. Somehow some valid string are not match. If someone could help me, please also explain to me what is the diff between ?: and ?=

The string I tried:

  • test123
  • test_1 (this one is not working with the code above) I tried to put {1,} but then some other testing string is not match.
  • test_a1
  • te_st_12
  • h1_h1
  • t11
  • t11a
È stato utile?

Soluzione

Try the below regex:

if (preg_match('/^[a-z]((?!__)[a-z\d_])+[a-z\d]$/i', $str)) {
  echo 'matched';
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top