Last active
October 5, 2015 12:16
-
-
Save danielpereirabp/4b37984360e6dae5ec6a to your computer and use it in GitHub Desktop.
PHP PCRE - How to validate complex passwords using regular expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* PHP PCRE - How to validate complex passwords using regular expressions | |
*/ | |
function valid_pass($candidate) { | |
if (!preg_match_all('$\S*(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $candidate)) | |
return FALSE; | |
return TRUE; | |
} | |
/* | |
Explaining $\S*(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$ | |
$ = beginning of string | |
\S* = any set of characters | |
(?=\S{8,}) = of at least length 8 | |
(?=\S*[a-z]) = containing at least one lowercase letter | |
(?=\S*[A-Z]) = and at least one uppercase letter | |
(?=\S*[\d]) = and at least one number | |
(?=\S*[\W]) = and at least a special character (non-word characters) | |
$ = end of the string | |
*/ | |
$password = 'mypassword01'; | |
if(valid_pass($password)) | |
echo "$password is a valid password" . PHP_EOL; | |
else | |
echo "$password is NOT a valid password" . PHP_EOL; | |
$password = 'myP@ssword01'; | |
if(valid_pass($password)) | |
echo "$password is a valid password" . PHP_EOL; | |
else | |
echo "$password is NOT a valid password" . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment