PHP Regex for a string with alphanumeric and special characters

老子叫甜甜 提交于 2019-12-11 05:49:59

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/40120488/php-regex-for-a-string-with-alphanumeric-and-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!