Summary of PHP random generation String Program method

Source: Internet
Author: User
Tags chr strlen

Number of randomly generated numbers

Mt_rand () function

The code is as follows Copy Code

$num = Mt_rand (0,9999999);

But if I want to randomly generate strings how to operate, the Web site finds a way.

The code is as follows Copy Code

function Random ($length) {
Srand (Date ("S"));
$possible _charactors = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$string = "";
while (strlen ($string) < $length) {
$string. = substr ($possible _charactors, (rand ()% (strlen ($possible _charactors)), 1);
}
return ($string);
}

Example 2

  code is as follows copy code

function Random_string ($length, $max =false)
{
  if (Is_int ($max) && $max > $length)
  {
     $length = Mt_rand ($length, $max);
 }
  $output = ';
 
  for ($i =0 $i < $length $i + +)
  {
    $which = Mt_rand (0,2);
&nb sp;  
    if ($which = = 0)
    {
      $ Output. = Mt_rand (0,9);
   }
    elseif ($which = = 1)
    {
      $output. = Chr ( Mt_rand (65,90));
   }
    Else
    {
      $output. = Chr (Mt_rand 97,122 ));
   }
 }
  return $output;
}

Example 3

The code is as follows Copy Code

<?php
Description: The method of generating random strings in PHP
Finishing: Http://www.111cn.net
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); To disrupt an 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);
Echo $str;
?>


Note: The incoming parameter is the length of the random string you want to generate.

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.