如何使用PHP从给定的字符串生成简单的随机密码?
在本文中,我们将看到如何使用给定的字符串生成随机密码。我们给出了一个字符串,任务是从中生成一个随机密码。
例子:
Input: abgADKL123
Output: abgADKL123
Input: geeksforgeeks
Output: egksegsfroeke
为了实现这一点,我们使用以下方法。
方法 1:在这种方法中,我们使用PHP rand()函数并创建一个临时变量,并使用 for 循环从给定的字符串创建随机字符并将该字符连接到临时变量。下面是这个方法的实现。
PHP代码:
PHP
$str_length){
$len = $str_length;
}
// Iterate $len times so that the
// resulting string's length is
// equal to $len
for($i = 0; $i < $len; $i++){
// Concatenate random character
// from $str with $pass
$pass .= $str[rand(0, $str_length)];
}
return $pass;
}
// Print password of length 5 from
// the given string
$str = "GeeksForGeeks";
echo get_password($str, 5) . "\n
";
// Print password of length 15 from
// the given string
$str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
echo get_password($str, 15) ."\n
";
// Print password if the length
// is not given
echo get_password($str) . "\n
";
?>
PHP
$str_length){
$len = $str_length;
}
// Shuffle the string
$pass = str_shuffle($str);
// Extract the part of string
$pass = substr($pass, 0, $len);
return $pass;
}
// Print password of length 5 from
// the given string
$str = "GeeksForGeeks";
echo get_password($str) . "\n
";
// Print password of length 15 from
// the given string
$str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
echo get_password($str, 15) ."\n
";
// Print password if the length is
// not given
echo get_password($str) . "\n
";
?>
输出:
skGse
iWwf9jWZZE9ZL7O
GhRQ8zK4wpX93srUj1LhjsBEeBwBwo4Bh43RyZeSFZbwjVoonkKBgfXiBrEpY
方法二:在这种方法中,我们使用PHP的str_shuffle ()函数,然后我们使用substr() 函数来提取给定字符串的一部分。
PHP代码:
PHP
$str_length){
$len = $str_length;
}
// Shuffle the string
$pass = str_shuffle($str);
// Extract the part of string
$pass = substr($pass, 0, $len);
return $pass;
}
// Print password of length 5 from
// the given string
$str = "GeeksForGeeks";
echo get_password($str) . "\n
";
// Print password of length 15 from
// the given string
$str =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
echo get_password($str, 15) ."\n
";
// Print password if the length is
// not given
echo get_password($str) . "\n
";
?>
输出:
oeFssGkeGrkee
rxIhAjCi47wgW1z
r4LZQqlOFGU36i7gEAtzwsnduNXhHKD92ajpxBJc1MRvVmbyeokPIWfCTSY85