Vajira Lasantha Vajira Lasantha - 1 year ago 71
PHP Question

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?


Answer Source

Here you go, using lookaheads to verify your conditions:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download