How to create a password with atleast one alphabet,one digit and one special character and minimum length of the string is 8 using Regular expression in php
            Asked
            
        
        
            Active
            
        
            Viewed 715 times
        
    1 Answers
0
            
            
        Regex is useful for matching string, not to create them.
You can use this code to generate a password matching your requirement:
<?php
// Generate a password of length = Max(8, $len)
function generatePassword($len)
{
    $lower = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
    $upper = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $specials = array('!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\\',']','^','_','`','{','|','}','~');
    $digits = array('0','1','2','3','4','5','6','7','8','9');
    $all = array($lower, $upper, $specials, $digits);
    $pwd = $lower[array_rand($lower, 1)];
    $pwd = $pwd . $upper[array_rand($upper, 1)];
    $pwd = $pwd . $specials[array_rand($specials, 1)];
    $pwd = $pwd . $digits[array_rand($digits, 1)];
    for($i = strlen($pwd); $i < max(8, $len); $i++)
    {
        $temp = $all[array_rand($all, 1)];
        $pwd = $pwd . $temp[array_rand($temp, 1)];
    }
    return str_shuffle($pwd);
}
echo generatePassword(8);
 
    
    
        Thomas Ayoub
        
- 29,063
- 15
- 95
- 142
