Home >Backend Development >PHP Tutorial >A simple implementation method for PHP to generate a specified random string, PHP generates a string_PHP tutorial

A simple implementation method for PHP to generate a specified random string, PHP generates a string_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:58:33800browse

A simple implementation method for PHP to generate a specified random string, PHP to generate a string

The example in this article describes a simple implementation method for PHP to generate a specified random string. Share it with everyone for your reference. The specific analysis is as follows:

This is a simple function with no mandatory settings for the generated content. Therefore, when the length of the generated string is small, there will be situations where there are no specified type characters. Of course, it is very simple to modify, so I won’t add it here.

/**
 * @param string $type
 * @param $length
 * @return string
 */
function randomString($type="number,upper,lower",$length){
  $valid_type = array('number','upper','lower');
  $case = explode(",",$type);
  $count = count($case);
  //根据交集判断参数是否合法
  if($count !== count(array_intersect($case,$valid_type))){
    return false;
  }
  $lower = "abcdefghijklmnopqrstuvwxyz";
  $upper = strtoupper($lower);
  $number = "0123456789";
  $str_list = "";
  for($i=0;$i<$count;++$i){
    $str_list .= $$case[$i];
  }
  return substr(str_shuffle($str_list),0,$length);
}
echo randomString("number,upper,lower",12);

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/977791.htmlTechArticleA simple implementation method for PHP to generate a specified random string. PHP generates a string. This article describes the example of PHP generating a specified random character. Simple implementation method of string. Share it with everyone for your reference. Tool...
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