Home  >  Article  >  Backend Development  >  Summary of some methods for randomly generating strings in PHP_PHP Tutorial

Summary of some methods for randomly generating strings in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 16:57:45673browse

I have talked about generating random passwords before. Now I will introduce to you some commonly used functions for generating random strings. These are our custom functions. Of course, there are also functions built into the system, but they are relatively simple. .

mt_rand function

Example

In this case, we return some random numbers:

The code is as follows Copy code
 代码如下 复制代码

echo(mt_rand());
echo(mt_rand());
echo(mt_rand(10,100));
?>
输出类似:

3150906288
513289678
35

echo(mt_rand());
echo(mt_rand());
echo(mt_rand(10,100));
?>
The output is similar to:

3150906288
513289678
35
 代码如下 复制代码

function roll () {
  return mt_rand(1,6);
  }

echo roll();

function roll ($sides) {
  return mt_rand(1,$sides);

}
  echo roll(6); // roll a six-sided die
  echo roll(10); // roll a ten-sided die
  echo roll(20); // roll a twenty-sided die

Let’s take a look at an example of the mt_rand function.

The code is as follows Copy code
 代码如下 复制代码

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;
}

$str = genRandomString(25);
$str .= "
";
$str .= genRandomString(25);
$str .= "
";
$str .= genRandomString(25);
$str .= "

";

echo $str;
?>


程序输出如下:


DmLVAmDkEJz8wHXRCNwzvANlB
BILZSA19YyuSVcR17KrrZsOKO
inlWlQF0GSabN3l589y9s16Gg

function roll () {
​return mt_rand(1,6);
} echo roll(); function roll ($sides) {
​return mt_rand(1,$sides); }
echo roll(6); // roll a six-sided die
echo roll(10); // roll a ten-sided die
echo roll(20); // roll a twenty-sided die
The above can only generate simple pure numbers, not letters or numbers and letters. Next we need to use a custom function
The code is as follows Copy code
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); //Shuffle the array

$output = "";
for ($i=0; $i<$len; $i++) {
           $output .= $chars[mt_rand(0, $charsLen)];
}

Return $output;
} $str = genRandomString(25);
$str .= "
";
$str .= genRandomString(25);
$str .= "
";
$str .= genRandomString(25);
$str .= "

"; echo $str;
?>
The program output is as follows:
DmLVAmDkEJz8wHXRCNwzvANlB
BILZSA19YyuSVcR17KrrZsOKO
inlWlQF0GSabN3l589y9s16Gg

Example

The length of the random string generated by default is 5, and the generated string contains: numbers + uppercase letters

Function:

1. Generate a random string of specified length

2. Flexibly select the complexity of the generated random string

* @param string $type Random code type: 0, numbers + uppercase letters; 1, numbers; 2, lowercase letters; 3, uppercase letters; 4, special characters; -1, numbers + uppercase and lowercase letters + special characters +------------------------------------------------- ----------
The code is as follows
 代码如下 复制代码

/**
  +----------------------------------------------------------
 * 生成随机字符串
  +----------------------------------------------------------
 * @param int       $length  要生成的随机字符串长度
 * @param string    $type    随机码类型:0,数字+大写字母;1,数字;2,小写字母;3,大写字母;4,特殊字符;-1,数字+大小写字母+特殊字符
  +----------------------------------------------------------
 * @return string
  +----------------------------------------------------------
 */
function randCode($length = 5, $type = 0) {
    $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode(",", $arr);
    } else if ($type == "-1") {
        $string = implode(",", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
$str[$i] = $string[rand(0, $count)];
$code .= $str[$i];
}
return $code;
}

Copy code

/**
+------------------------------------------------- ----------
* Generate random string

+------------------------------------------------- ----------
代码如下 复制代码

function make_password( $length = 8 )
{
// 密码字符集,可任意添加你需要的字符
$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', '!',
'@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
'[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
    '.', ';', ':', '/', '?', '|');

    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array_rand($chars, $length);

    $password = '';
    for($i = 0; $i < $length; $i++)
{
// 将 $length 个数组元素连接成字符串
$password .= $chars[$keys[$i]];
}

return $password;
}

* @param int $length The length of the random string to be generated
* @return string<🎜> +------------------------------------------------- ----------<🎜> ​*/<🎜> function randCode($length = 5, $type = 0) {<🎜> $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|" ); If ($type == 0) {          array_pop($arr);          $string = implode(",", $arr); } else if ($type == "-1") {          $string = implode(",", $arr); } else {           $string = $arr[$type]; } $count = strlen($string) - 1; for ($i = 0; $i < $length; $i++) {<🎜>          $str[$i] = $string[rand(0, $count)];<🎜>            $code .= $str[$i];<🎜> }<🎜> Return $code;<🎜> }<🎜> <🎜> <🎜> <🎜> <🎜>Example<🎜> <🎜>1. Preset a character array $chars, including a – z, A – Z, 0 – 9, and some special characters <🎜> 2. Use array_rand() to randomly select $length elements from the array $chars<🎜> 3. According to the obtained key name array $keys, take out the characters from the array $chars and concatenate the string. The disadvantage of this method is that the same characters will not be retrieved repeatedly. <🎜>
The code is as follows<🎜> Copy code<🎜> <🎜>
<🎜>function make_password( $length = 8 )<🎜> {<🎜> // Password character set, you can add any characters you need <🎜> $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', '!', <🎜> '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_', <🎜> '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',', '.', ';', ':', '/', '?', '|'); // Randomly select $length array element key names in $chars $keys = array_rand($chars, $length); $password = ''; for($i = 0; $i < $length; $i++) {                // Concatenate $length array elements into string            $password .= $chars[$keys[$i]]; } return $password; }

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631493.htmlTechArticleI have talked about generating random passwords before. Now let me introduce to you some commonly used functions for generating random strings. , these are our custom functions, of course there are also system built-in functions...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn