Hello, there is a regular checker for checking nick when registering ~^[^-_][a-zA-Z_\-0-9]*$~u but for some reason the user can enter this # nickname, the hashtag is approved only if it costs like The first character, do not tell me how to fix it?

  • one
    Perhaps you want to make the first character different from - and _ ? Use ~^(?![-_])[a-zA-Z0-9_-]*$~u , or even ~^(?:[a-zA-Z0-9][\w-]*)?$~ . - Wiktor Stribiżew
  • 2
    Your nickname can start with just about anything except "-" and "_", judging by [^-_] - MedvedevDev

2 answers 2

The [^-_] pattern is an exclusive character class, it finds any character that is completely different from the sign - and _ (that is, so many characters).

Delete it:

 ~^[a-zA-Z_0-9-]*$~ 

This expression is easily shortened to

 ~^[\w-]*$~ 

See the demo

If empty strings are not allowed, replace the quantifier * with + :

 ~^[\w-]+$~ 

Details

  • ^ -start
  • [\w-]* - 0 or more letters / numbers / _ ( \w ) and / or -
  • $ - end of line.

By the way, if you want to make $ find the position directly at the end of the line, use the D modifier: ~^[\w-]*$~D

  • The u modifier is lost in the second version. - sanmai
  • @sanmai In the original version of the expression - ~^[^-_][a-zA-Z_\-0-9]*$~u - there is not a single Unicode character. I suppose only ASCII is allowed. The u modifier will allow \w find any letters and digits of Unicode. Wait for an answer. - Wiktor Stribiżew
  • Thank you, but do not tell me how to make it possible to add "-" and "_" to the beginning of the nickname? Simply, in principle, I was satisfied with my expression, just in the beginning I could enter “#” - Vladimir
  • @ Vladimir Seems, you just need to delete (?![-_]) : ~^[a-zA-Z_0-9-]*$~ / ~^[\w-]*$~D - Wiktor Stribiżew

Let the nickname begin only on a letter, and contains letters, numbers and signs "_" and "-"

 ~^[a-zA-Z][a-zA-Z_\-0-9]*$~u