我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
function generateRandomString($length = 10, $hasNumber = true, $hasLowercase = true, $hasUppercase = true): string
{
$string = '';
if ($hasNumber)
$string .= '0123456789';
if ($hasLowercase)
$string .= 'abcdefghijklmnopqrstuvwxyz';
if ($hasUppercase)
$string .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($x = $string, ceil($length / strlen($x)))), 1, $length);
}
和使用:
echo generateRandomString(32);
具有上面讨论的一些函数的类。
$options['numeric'] = true;
$options['uppercase'] = true;
$options['lowercase'] = true;
$new = new RandomString($options);
class RandomString
{
/**
* @var array
*/
private $default = ['numeric' => true, 'uppercase' => true, 'lowercase' => true];
/**
* @var array
*/
private $options;
/**
* array
*/
private $whitelist = ['numeric', 'uppercase', 'lowercase'];
/**
* RandomString constructor.
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->options = $this->default;
if(!empty($options))
{
$options = array_intersect_key($options, array_flip($this->whitelist));
if(empty($options))
{
$this->options = $this->default;
}else
{
$this->options = $options;
}
}
}
/**
* @return string
*/
private function returnCharacters(){
$options = $this->options;
$numbers = '0123456789';
$uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$lowercase = "abcdefghijklmnopqrstuvwxyz";
$characters = '';
if(isset($options['numeric']) && $options['numeric'] === true){
$characters .= $numbers;
}
if(isset($options['uppercase']) && $options['uppercase'] === true){
$characters .= $uppercase;
}
if(isset($options['lowercase']) && $options['lowercase'] === true){
$characters .= $lowercase;
}
return $characters;
}
/**
* @param $length
* @param $quantity
* @return string
*/
public function randomString($length, $quantity) {
$string = '';
$characters = $this->returnCharacters();
for ($j = 0; $j < $quantity; $j++) {
for($i = 0; $i < $length; $i++){
$string .= $characters[mt_rand(0, strlen($characters) - 1)];
}
$string .= "\n";
}
return $string;
}
/**
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* @return mixed
*/
public function getWhitelist()
{
return $this->whitelist;
}