我试图在PHP中创建一个随机字符串,我得到绝对没有输出:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring = $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

如果您非常害怕输入字母表中的字母,不关心字符串安全性,并且只对字母感兴趣,那么这里有一个简单的解决方案

$alphabets = range ("a", "z");
shuffle ($alphabets);
$randomString = substr(implode ("", $alphabets), 3, 17); // adjust according to desired length 

其他回答

下面的函数生成任意长度的伪字符串。

/**
 * Returns random string of a given length.
 */
function get_random_string($length) {
  $pull = [];
  while (count($pull) < $length) {
    $pull = array_merge($pull, range(0, 9), range('a', 'z'), range('A', 'Z'));
  }
  shuffle($pull);
  return substr(implode($pull), 0, $length);
}

我想要特定字符和预设长度的伪随机字符串。我希望当前版本的PHP具有最高质量的伪随机性,此时它可以是v5、v6、v7或v8,并且可以使用默认配置或特殊配置。为了解决这种混乱,我在这里选取了其他几个答案,并包含了函数可用性条件。

使用。要全局使用它,给$VALID_ID_CHARS赋值你想要的字符,然后调用它:

$VALID_ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$myNewRandomId = makeId(6);
function makeId($desiredLen)
{
    global $VALID_ID_CHARS;
    if ($desiredLen < 1) {
        throw new \RangeException("Length must be a positive integer");
    }
    $vLen = 0;
    if (function_exists('mb_strlen')) {
        $vLen = mb_strlen($VALID_ID_CHARS, '8bit') - 1;
    } else {
        $vLen = strlen($VALID_ID_CHARS) - 1;
    }
    if (function_exists('random_int')) {
        $pieces = [];
        for ($i = 0; $i < $desiredLen; ++$i) {
            $pieces[] = $VALID_ID_CHARS[random_int(0, $vLen)];
        }
        return implode('', $pieces);
    }
    if (function_exists('openssl_random_pseudo_bytes')) {
        $random = openssl_random_pseudo_bytes($desiredLen);
        $id = '';
        for ($i = 0; $i < $desiredLen; ++$i) {
            $id .= $VALID_ID_CHARS[ord($random[$i]) % $vLen];
        }
        return $id;
    }
    http_response_code(500);
    die('random id generation failed. either random_int or openssl_random_pseudo_bytes is needed');
}

如果您非常害怕输入字母表中的字母,不关心字符串安全性,并且只对字母感兴趣,那么这里有一个简单的解决方案

$alphabets = range ("a", "z");
shuffle ($alphabets);
$randomString = substr(implode ("", $alphabets), 3, 17); // adjust according to desired length 

短的方法。

这里有一些生成随机字符串的最短方法

<?php
echo $my_rand_strng = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), -15); 

echo substr(md5(rand()), 0, 7);

echo str_shuffle(MD5(microtime()));
?>

具有上面讨论的一些函数的类。

$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;
    }