简体   繁体   中英

PHP Regex for a string with alphanumeric and special characters

I tried and could not find an answer for this issue, so I'm asking this question.

I need to create a regex for password validation and it must have following conditions.

  • At least one letter
  • At least one number
  • At least one special letter ~ ! ^ ( ) { } < > % @ # & * + = _ -
  • Must not contain $ ` , . / \\ ; : ' " |
  • Must be between 8-40 characters
  • No spaces

I have created following regex but it does not work properly.

preg_match('/[A-Za-z\d$!^(){}?\[\]<>~%@#&*+=_-]{8,40}$/', $newpassword)

Can somebody please help me to fix this regex properly?

Thanks.

Here you go, using lookaheads to verify your conditions:

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!^(){}<>%@#&*+=_-])[^\s$`,.\/\\;:'"|]{8,40}$

Let's break it down a little, because it's kinda nasty-looking:

  • The ^ asserts that it's at the start of the string.
  • The first lookahead, (?=.*[a-zA-Z]) , verifies that it contains at least one letter (upper or lower).
  • The second, (?=.*\\d) , verifies that it contains at least one digit.
  • The third, (?=.*[~!^(){}<>%@#&*+=_-]) , verifies that it contains at least one character from your special characters list.
  • Finally, [^\\s$,.\\/\\\\;:'"|]{8,40}$ verifies that the entire string is between 8 and 40 characters long, and contains no spaces or illegal characters by using an inverted character class.

Demo on Regex101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM