PHP Strings
Generating a Random String
Problem
Solution
function str_rand($length = 32,
$characters = ↵
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
if (!is_int($length) || $length < 0) {
return false;
}
$characters_length = strlen($characters) - 1;
$string = '';
for ($i = $length; $i > 0; $i--) {
$string .= $characters[mt_rand(0, $characters_length)];
}
return $string;
}
Discussion
PHP has native functions for generating random numbers, but nothing for random
strings. The str_rand() function returns a 32-character string constructed from letters
and numbers. Pass in an integer to change the length of the returned string. To use an alternative set of characters, pass them as a string as the second argument.
For example, to get a 16-digit Morse Code:
print str_rand(16, '.-');
No comments:
Post a Comment