Vajira Lasantha
Vajira Lasantha

Reputation: 2513

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.

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.

Upvotes: 2

Views: 4642

Answers (1)

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

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

Upvotes: 5

Related Questions