PHP開発-ランダムな文字列を作成する方法

方法1
function randStrGet($len)
{
$chars=”ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz-=/?~!@#$%^&*()”; // characters to build the password from
$strbak=””;
for(;$len >= 1;$len–)
{
$position=rand()%strlen($chars);
$strbak.=substr($chars,$position,1);
}
return $strbak;
}

方法2
function generatePasswd( $length = 8 ) {
$chars = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}~`+=,.;:/?’;
$pwdinfo= ”;
while (strlen($pwdinfo) < $length)
{
$pwdinfo .= $chars[ mt_rand(0, strlen($chars) – 1) ];
}
return $pwdinfo;
}

方法3

function genRandomString($len)
{
$chars = 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”, “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”, “0”, “1”, “2”,
“3”, “4”, “5”, “6”, “7”, “8”, “9”, “!”, “@”, “#”, “$”,
“%”, “^”, “&”, “*”, “(“, “)”, “-“, “_”, “[“, “]”, “{“,
“}”, “~”, “`”, “+”, “=”, “,”, “.”, “:”, “;”, “/”, “?”
);
$charsLen = count($chars) – 1;
shuffle($chars);
$output = “”;
for ($i=0; $i<$len; $i++)
{
$output .= $chars[mt_rand(0, $charsLen)];
}
return $output;
}

echo “method1:”.randStrGet(30).”<br />”;
echo “method2:”.generatePasswd(30).”<br />”;
echo “method3:”.genRandomString(30).”<br />”;

Comments are closed.