教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 很实用的3个PHP随机字符串函数生成器

很实用的3个PHP随机字符串函数生成器

发布时间:2014-07-20   编辑:jiaochengji.com
很实用的3个PHP随机字符串函数生成器
复制代码 代码如下:
<?php
函数1:
/*
* 产生随机字符串
*
* 产生一个指定长度的随机字符串,并返回给用户
*
* @access public
* @param int $len 产生字符串的位数
* @return string
*/
function randStr($len)
{
    $chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz-=/?~!@#$%^&*()"; // characters to build the password from
    $string="";
    for(;$len >= 1;$len--)
    {
        $position=rand()%strlen($chars);
        $string.=substr($chars,$position,1);
    }
    return $string;
}

 

函数2:
function generate_password( $length = 8 ) {
// 密码字符集,可任意添加你需要的字符
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}~`+=,.;:/?';
$password = '';
//for ( $i = 0; $i < $length; $i++ )
while (strlen($password) < $length)
{
// 这里提供两种字符获取方式
// 第一种是使用 substr 截取$chars中的任意一位字符;
// 第二种是取字符数组 $chars 的任意元素
// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $password;
}

函数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 "第一个:".randStr(50)."<br />";
echo "第二个:".generate_password(50)."<br />";
echo "第三个:".genRandomString(50)."<br />";
?>

产生的随机字符串分别为:
第一个:1A5jOOJmM9wzMVFSJr5Utk)kpU^YmSN(Tig5unC~FyoRDt8K3?
第二个:e/$g[UE@Qm*tAsvNcGKbyfCoo,@?NcL0%)+Kkao-m]jtGxvWik
第三个:_}vz8+PIjkf]2Z*]^C?^H*a7V5thbSXKwuO)R4?I^_vC4G;Lp[

您可能感兴趣的文章:
php生成指定位数(长度)的随机字符串
php生成随机产生六位数密码的代码
php生成随机数的例子
PHP批量更新数据库的示例代码
php生成随机数字和字母的实例代码
php随机生成4位数字验证码
php生成N个不重复的随机数
用PHP生成随机数的函数
php生成随机字符串的函数
生成随机用户名与密码的php函数

关键词: 随机字符串   
[关闭]
~ ~