在PHP中使用正则表达式进行用户名验证

I am trying to validate a USERNAME in PHP using Regular Expression. But I am failed. My pattern is: /[^a-z0-9_]/

Rules:

  • username must start number or small letters
  • username support number, small letters and _
  • the end of username character is not be _

The following pattern will work: ^[a-z0-9][a-z0-9_]*[a-z0-9]$

  • ^[a-z0-9]: first character may not be an underscore
  • [a-z0-9_]*: all the others may be anything...
  • [a-z0-9]$: ...except the last one which can't be an underscore.

Assuming the minimum number of characters is two (if less than three, the underscore never would be permitted), here is the correct pattern:

^[a-z0-9][a-z0-9_]*[a-z0-9]$

First character is small letters or digit (there can be more of them, that's why the + sign. Then any amount (including zero) of characters including underscore. At the end again, at least one letter or digit.

You can test it here:

https://regex101.com/r/C1zPfu/1

You do not want username of two letters or username that has unlimited characters, do you? Consider this solution if you need to limit the number of characters in your username under your situation:

/^[a-z0-9][a-z0-9_]{2,28}[a-z0-9]$/

https://www.tinywebhut.com/regex/4

The part [a-z0-9] exactly matches one character which can be only small letter or number. The middle part [a-z0-9_]{2,28} matches any small letter or number up to 2 or 28 characters including underscore. The final part [a-z0-9] exactly matches one character which can be only small letter or number. Therefore, this regular expression matches username that has at least 4 characters and 30 characters at the most. If you change your mind and want to include both small and capital letters, you'll have to add a modifier i:

/^[a-z0-9][a-z0-9_]{2,28}[a-z0-9]$/i

https://www.tinywebhut.com/regex/5