Hello, there is a regular ~^[a-zA-Z_0-9-]*$~ which I sketched with difficulty, because I don’t understand them. Do not tell me how you can change it so that the text could not begin with the symbols _ and - ?

  • one
    ~^[a-zA-Z0-9][a-zA-Z_0-9-]*$~ - rjhdby
  • one
    Can your text be blank? - Visman
  • @Visman is not, this is a nickname. For example user_-123 - Vladimir
  • @Vladimir, then the option from rjhdby is fine. - Visman
  • @rjhdby transfer in response, put a tick - Vladimir

1 answer 1

that the text could not begin with the characters _ and - ?

The easiest option is to simply write out the first characters allowed separately:

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

I draw attention to the fact that the regular line has ceased to correspond to the empty string. If you need to allow an empty string, you will have to check it separately:

 ~^([a-zA-Z0-9][a-zA-Z_0-9-]*)?$~ 

Another disadvantage of this approach is that if the allowed characters suddenly change, you will have to change them in two places.

In general, I recommend another option, namely, to prohibit specific first characters:

 ~^(?![-_])[a-zA-Z_0-9-]*$~