Home  >  Article  >  Backend Development  >  PHP randomly generates string examples to explain

PHP randomly generates string examples to explain

巴扎黑
巴扎黑Original
2017-08-11 13:45:341054browse

This article mainly introduces the method of generating random strings in PHP in detail. It has certain reference value. Interested friends can refer to it.

The example of this article is to share with you the method of generating random strings in PHP. The specific code of the string is for your reference. The specific content is as follows


function generateRandomString($length = 10) { 
  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
  $randomString = ''; 
  for ($i = 0; $i < $length; $i++) { 
    $randomString .= $characters[rand(0, strlen($characters) - 1)]; 
  } 
  return $randomString; 
}

echo generateRandomString(20);


/**
 * 随机生成字符串
 * @param int $length
 * @return null|string
 */
private static function getRandChar($length = 8){
  $str = null;
  $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  $max = strlen($strPol)-1;
 
  for($i=0;$i<$length;$i++){
    $str.=$strPol[rand(0,$max)]; //rand($min,$max)生成介于min和max两个数之间的一个随机整数
  }
 
  return $str;
}

The above is the detailed content of PHP randomly generates string examples to explain. 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