Generate a random string.

@param integer $len
@param string $_charset
@return string
425246
public function str($len, $_charset = null) {
    if($_charset == null) {
      $_charset = $this->_charset;
    }

    $str = '';
    for ($i = 0; $i < $len; $i++) {
      $pos = $this->int(0,strlen($_charset)-1);
      $str .= $_charset[$pos];
    }
    return $str;
  }
185812
public static function random(int $length = 10, string $charList = '0-9a-zA-Z'): string
    {
        $charList = \count_chars(\preg_replace_callback('#.-.#', function (array $m) {
            return \implode('', \range($m[0][0], $m[0][2]));
        }, $charList), 3);
        $chLen = \strlen($charList);

        if ($length < 1) {
            throw new InvalidArgumentException('Length must be greater than zero.');
        }

        if ($chLen < 2) {
            throw new InvalidArgumentException('Character list must contain as least two chars.');
        }

        $res = '';
        for ($i = 0; $i < $length; $i++) {
            $res .= $charList[\random_int(0, $chLen - 1)];
        }

        return $res;
    }
1114865
public static function strRandom($length = 20, $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_')
    {
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[ rand(0, strlen($chars) - 1) ];
        }

        return $str;
    }
1195689
public static function generate($length = 10, $charlist = '0-9a-z')
	{
		$charlist = str_shuffle(preg_replace_callback('#.-.#', function($m) {
			return implode('', range($m[0][0], $m[0][2]));
		}, $charlist));
		$chLen = strlen($charlist);

		static $rand3;
		if (!$rand3) {
			$rand3 = md5(serialize($_SERVER), TRUE);
		}

		$s = '';
		for ($i = 0; $i < $length; $i++) {
			if ($i % 5 === 0) {
				list($rand, $rand2) = explode(' ', microtime());
				$rand += lcg_value();
			}
			$rand *= $chLen;
			$s .= $charlist[($rand + $rand2 + ord($rand3[$i % strlen($rand3)])) % $chLen];
			$rand -= (int) $rand;
		}
		return $s;
	}
331271
def random(length, chars=None):
    
    if chars is None:
        chars = string.ascii_letters + string.digits
    else:
        ensure_string(chars)
        if not chars:
            raise ValueError("character set must not be empty")

    if is_pair(length):
        length = randint(*length)
    elif isinstance(length, Integral):
        if not length > 0:
            raise ValueError(
                "random string length must be positive (got %r)" % (length,))
    else:
        raise TypeError("random string length must be an integer; "
                        "got '%s'" % type(length).__name__)

    return join(chars.__class__(), (choice(chars) for _ in xrange(length)))
862458
public function generateRandomString($length)
    {
        do {
            $bytes = base64_encode($this->random->nextBytes($length));
            $string = substr(strtr($bytes, array('+' => '', '/' => '', '=' => '')), 0, $length);
        } while (strlen($string) < $length);
        return $string;
    }
228328
public static function get_random_string($length = 10, $chars)
	{
	    $random_string = '';
	    
	    for($i = 0; $i < $length; $i++)
	    {
	        $index = rand(0, strlen($chars) - 1);
	        $random_string .= $chars{$index};
	    }
	    
	    return $random_string;
	}
1069751
public static function random($length = 64, $characters = self::ALNUM)
    {
        static $random_generator = null;

        if (null === $random_generator) {
            $random_generator = is_callable('mt_rand') ? 'mt_rand' : 'rand';
        }

        $len = strlen($characters);
        return join(
            '',
            array_map(
                function () use ($characters, $len, $random_generator) {
                    return $characters{$random_generator(0, $len - 1)};
                },
                range(0, $length - 1)
            )
        );
    }
564023
protected function createString( $length, $pool )
	{
		$random	= array();
		$input	= array();
		for( $i=0; $i<strlen( $pool ); $i++ )
			$input[] = $pool[$i];

		if( $this->unique )
		{
			for( $i=0; $i<$length; $i++ )
			{
				$key = array_rand( $input, 1 );
				if( in_array( $input[$key], $random ) )
					$i--;
				else
					$random[] = $input[$key];
			}
		}
		else
		{
			if( $length <= strlen( $pool ) )
			{
				shuffle( $input );
				$random	= array_slice( $input, 0, $length );
			}
			else
			{
				for( $i=0; $i<$length; $i++ )
				{
					$key = array_rand( $input, 1 );
					$random[] = $input[$key];
				}
			}
		}
		$random	= join( $random );
		return $random;
	}
1361807
public static function _randomPassword ($length = self::DEFAULT_PASSWORD_LENGTH, $charset = self::DEFAULT_PASSWORD_CHARACTERS)
	{
		
		// Set password variable
		
		$password	= '';

		// Set i to the password length
		
		$i = $length;

		// Loop until the password is the desired length
		
		while ($i > 0)
		{
			
			// Choose a random character from the charset
			
			$char = $charset[mt_rand (0, strlen ($charset) -1)];

			// Make sure that the first character of the password is a number or letter
			
			if ($password == '' && !preg_match('/[0-9A-Za-z]/', $char))
			{
				continue;
			}
			
			// Add the character to the password
			
			$password .= $char;

			// Decrement rounds
			
			$i--;

		}

		// Return the password
		
		return $password;

	}
140195
def random_hex(length):
    
    charset = ''.join(set(string.hexdigits.lower()))
    return random_string(length, charset)
599538
private static function generateRandomString($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';

        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $string;
    }
1294873
function random(array, len) {
  const size = array.length;
  const randomIndexes = crypto.randomBytes(len).toJSON().data;
  return randomIndexes.map((char) => array[char % size]).join('');
}
1237292
protected function rand($chars, $length)
    {
        $string = '';
        $max    = $this->len($chars) - 1;

        $i = 0;
        while($i < $length)
        {
            $string .= $chars[\random_int(0, $max)];
            $i++;
        }

        return $string;
    }
765793
public static function randStr($len, $easyRead = false) {
		if ($easyRead) {
		    $str = 'ab23456789abcdefghzykxmnwpqrstuvwxyz'; // 人眼容易识别的字母数字
		} else {
			$str = '0123456789abcdefghijklmnopqrstuvwxyz';
		}

		$r = '';
		for ($i = 0; $i < $len; $i++) {
			$r .= $str[mt_rand(0, 35)];
		}

		return $r;
	}
216735
public static function random_string(int $length=10, $soup=null) {
		if ($length < 1) {
			return '';
		}

		if (\is_array($soup) && \count($soup)) {
			ref\cast::string($soup);

			$soup = \implode('', $soup);
			ref\sanitize::printable($soup);

			$soup = \preg_replace('/\s/u', '', $soup);
			$soup = \array_unique(mb::str_split($soup, 1, true));
			$soup = \array_values($soup);
			if (! \count($soup)) {
				return '';
			}
		}

		// Use default soup.
		if (! \is_array($soup) || ! \count($soup)) {
			$soup = constants::RANDOM_CHARS;
		}

		// Pick nine entries at random.
		$salt = '';
		$max = \count($soup) - 1;
		for ($x = 0; $x < $length; ++$x) {
			$salt .= $soup[static::random_int(0, $max)];
		}

		return $salt;
	}
776856
public static String random(int len) {
        final char[] chars = {'0', '1', '2', '3', '4',
                '5', '6', '7', '8', '9', '$', '#', '^', '&', '_',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z',
                '~', '!', '@'};

        final int max = chars.length;
        Random r = new Random();
        StringBuilder sb = new StringBuilder(len);
        while(len-- > 0) {
            int i = r.nextInt(max);
            sb.append(chars[i]);
        }
        return sb.toString();
    }