Summary of some methods for randomly generating strings in php

Source: Internet
Author: User
Tags character set

Mt_rand function

Example

In this example, we will return some random numbers:

The code is as follows: Copy code

<? Php
Echo (mt_rand ());
Echo (mt_rand ());
Echo (mt_rand (10,100 ));
?>
The output is similar:

3150906288
513289678
35

Let's take a look at the mt_rand function instance.

The code is as follows: Copy code

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

All of the above can only generate simple numbers, not letters, numbers, and letters. Now we need to use a user-defined function.

The code is as follows: Copy code

<? Php
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); // disrupt the array
   
$ Output = "";
For ($ I = 0; $ I <$ len; $ I ++ ){
$ Output. = $ chars [mt_rand (0, $ charsLen)];
    }
   
Return $ output;
}

$ Str = genRandomString (25 );
$ Str. = "<br/> ";
$ Str. = genRandomString (25 );
$ Str. = "<br/> ";
$ Str. = genRandomString (25 );
$ Str. = "<br/> ";

Echo $ str;
?>


The program output is as follows:


DmLVAmDkEJz8wHXRCNwzvANlB
BILZSA19YyuSVcR17KrrZsOKO
InlWlQF0GSabN3l589y9s16Gg

Example

The default length of a random string is 5. The generated string contains digits and uppercase letters.

Function:

1. Generate a random string of the specified length

2. Flexible selection of the complexity of the generated random string

The code is as follows: Copy code

/**
+ ----------------------------------------------------------
* Generate random strings
+ ----------------------------------------------------------
* @ Param int $ length the length of the random string to be generated
* @ Param string $ type random code type: 0, number + upper-case letter; 1, Number; 2, lower-case letter; 3, upper-case letter; 4, Special character;-1, numbers + uppercase/lowercase letters + Special characters
+ ----------------------------------------------------------
* @ 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. Extract the string from the array $ chars based on the obtained key name array $ keys. The disadvantage of this method is that the same characters are not repeated.

The code is as follows: Copy code

Function make_password ($ length = 8)
{
// Password character set, which can be any character 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 ', '! ',
'@', '#', '$', '%', '^ ','&','*','(',')','-', '_',
'[', ']', '{', '}', '<', '> ','~ ', ''',' + ',' = ',',',
'.',';',':','/','? ',' | ');

// Random $ length array element key names in $ chars
$ Keys = array_rand ($ chars, $ length );

$ Password = '';
For ($ I = 0; $ I <$ length; $ I ++)
    {
// Concatenate $ length array elements into strings
$ Password. = $ chars [$ keys [$ I];
    }

Return $ password;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.