Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

peermydeen's avatar

PHP regex - combination of multiple condition

I have to do validation against the password by the following conditions

  1. Uppercase and Lowercase
  2. Numbers
  3. Special characters

among three any two combination is enough to meet my requirements. It must be achieved by regex.

E.g 'password' => 'required|min:8|regex:/^XXXXX$/',

0 likes
7 replies
peermydeen's avatar

@tykus Yes, It will be achieved by laravel build in validation rules. But i want to achieve it by regex.

TwentyHxte's avatar

You could just use the Laravel built in validation rules.

$request->validate([ 'password' => 'required|string', ]);

if its not what you really wanted the documentation could help you.

TwentyHxte's avatar

@peermydeen You could probably do it this way if you really want to use a regex:

^(?=.*[a-zA-Z])(?=.*[0-9]|.*[!@#\$%\^&\*]|.*[a-zA-Z]).{2,}$

Any string containing uppercase or lowercase letter and number or special characters should match.

1 like
peermydeen's avatar
peermydeen
OP
Best Answer
Level 1

@TwentyHxte Thanks for your answer. But it doesn't meet my requirements so, i made below logic to solve my issue.

$patterns = ['a-z', 'A-Z', '0-9', '`~!@#$%^&*()\-=_+\[\]\{\}\\|;:\'\",.\/<>?'];

$i = 0;
foreach ($patterns as $pattern) {
  // Enough to meet any two pattern
  if ($i == 2) {
    break;
  }

  if (preg_match('/[' . $pattern . ']/', $password)) {
    $i++;
  }
}
return ($i == 2) ? true : false;
1 like

Please or to participate in this conversation.