note 87487 added to function.rand
| From: | whatchildisthis at gmail dot com | Date: | Sun, 07 Dec 2008 00:00:24 +0000 |
| Subject: | note 87487 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-147775@lists.php.net to get a copy of this message | ||
I also enjoy making one-liners.
Here's a non-regular expression approach. It generates a random 32 character string consisting
of, by default, only A-Z, a-z, and 0-9, but you can change the value of $a for other characters. The
random string will be in variable $s after this line.
for ($s = '', $i = 0, $z = strlen($a =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')-1; $i != 32; $x =
rand(0,$z), $s .= $a{$x}, $i++);
If you don't want the same character to appear beside itself, use this:
for ($i = 0, $z = strlen($a =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')-1, $s = $a{rand(0,$z)},
$i = 1; $i != 32; $x = rand(0,$z), $s .= $a{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s),
$i=strlen($s));
For those of you who want both as a function, use this:
function rand_chars($c, $l, $u = FALSE) {
if (!$u) for ($s = '', $i = 0, $z = strlen($c)-1; $i < $l; $x = rand(0,$z), $s .=
$c{$x}, $i++);
else for ($i = 0, $z = strlen($c)-1, $s = $c{rand(0,$z)}, $i = 1; $i != $l; $x = rand(0,$z), $s .=
$c{$x}, $s = ($s{$i} == $s{$i-1} ? substr($s,0,-1) : $s), $i=strlen($s));
return $s;
}
string $c is the string of characters to use.
integer $l is how long you want the string to be.
boolean $u is whether or not a character can appear beside itself.
Examples:
rand_chars("ABCEDFG", 10) == GABGFFGCDA
rand_chars("ABCEDFG", 10, TRUE) == CBGFAEDFEC
----
Server IP: 64.71.164.2
Probable Submitter: 209.248.109.19
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/87487
Del: integrated -- https://master.php.net/note/delete/87487/integrated
Del: useless -- https://master.php.net/note/delete/87487/useless
Del: bad code -- https://master.php.net/note/delete/87487/bad+code
Del: spam -- https://master.php.net/note/delete/87487/spam
Del: non-english -- https://master.php.net/note/delete/87487/non-english
Del: in docs -- https://master.php.net/note/delete/87487/in+docs
Del: other reasons-- https://master.php.net/note/delete/87487
Reject -- https://master.php.net/note/reject/87487
Search -- https://master.php.net/manage/user-notes.php