Home  >  Article  >  Backend Development  >  Detailed explanation of php random string generation method

Detailed explanation of php random string generation method

墨辰丷
墨辰丷Original
2018-05-23 15:47:021770browse

This article mainly introduces the simple random string generation method in PHP, and analyzes the related techniques and precautions for PHP to generate random strings in the form of examples. Friends in need can refer to the following

The examples in this article describe PHP simple random string generation method. I share it with you for your reference. The details are as follows:

<?php
function rand_str($length,$p=&#39;all&#39;){
 $nums = &#39;0123456789&#39;;
 $lowers = &#39;abcdefghijklmnopqrstuvwxyz&#39;;
 $uppers = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;
 if ($p == &#39;all&#39;) {
 $src = $nums.$lowers.$uppers;
 } else {
 $src = &#39;&#39;;
 if (strpos($p, &#39;num&#39;) !== false)
  $src .= $nums;
 if (strpos($p, &#39;lower&#39;) !== false)
  $src .= $lowers;
 if (strpos($p, &#39;upper&#39;) !== false)
  $src .= $uppers;
 }
 return $src? substr(str_shuffle($src), 0, $length) : $src;
}
?>

I searched the Internet for PHP functions of random strings and found that most implementations use loops. --This is a bit inefficient. In php, there are various functions that you can't think of, but no one else can think of. The str_shuffle() function can easily randomize strings. However, it is better to encapsulate one, after all, there are People have the need to use only uppercase letters and numbers.

The second parameter of the function, num, lower, and upper, can be combined at will.

The real core statement is only one line

substr(str_shuffle($src), 0, $length)

The function is to shuffle the string $src and intercept the first $length characters.

The above is the entire content of this article, I hope it will be helpful to everyone learning helps.


Related recommendations:

PHPHow to format MYSQL to return float type_php tips

PHPA large summary of mathematical operation functions (classics worth collecting)_php skills

PHPArray function array_multisort() usage example analysis_php skills

The above is the detailed content of Detailed explanation of php random string generation method. For more information, please follow other related articles on the PHP Chinese website!

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