Skip to content

Instantly share code, notes, and snippets.

@vyspiansky
Last active May 13, 2024 11:55
Show Gist options
  • Save vyspiansky/bbe70a3ed80318a021346170576620b4 to your computer and use it in GitHub Desktop.
Save vyspiansky/bbe70a3ed80318a021346170576620b4 to your computer and use it in GitHub Desktop.
Validate a password using preg_match with regular expression
<?php
declare(strict_types=1);
/*
A pattern with multiple conditions:
- at least one digit.
- at least one lowercase letter (including special Scandinavian characters).
- at least one uppercase letter (including special Scandinavian characters).
- at least one character that is not a letter or a number (including special Scandinavian characters).
- a total length of a string is at least 12 characters.
Passwords with Scandinavian characters: aÅ#123456789, öB#123456789, öb#123456789, AÅ#123456789
*/
$pattern = '/^(?=.*[0-9])(?=.*[a-zæøåäö])(?=.*[A-ZÆØÅÄÖ])(?=.*[^a-zA-Z0-9æøåäöÆØÅÄÖ]).{12,}$/u';
$password = 'aÅ#123456789';
if (preg_match($pattern, $password)) {
echo 'Valid password';
} else {
echo 'Invalid password';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment