We help IT Professionals succeed at work.

PHP: 5 random characters

hankknight
hankknight asked
on
I want 5 random characters to be taken from these available options:
       ABCDEFGHJKLMNPQRSTUVWXYZ23456789

For example this could be randomly returned:
AAZB5

But this should never be returned:
I10O1
Comment
Watch Question

This, slightly modified, might do what you want.

http://www.webtoolkit.info/php-random-password-generator.html
Fixer of Problems
Most Valuable Expert 2014
Commented:
Here you go.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Random Characters</title>
</head>
<body>
<h1>Random Characters</h1>
<?php 

$srcstr = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
$dststr = "";

for($i = 0;$i < 5; $i++) {
	$j = rand(0, strlen($srcstr));
	$dststr .= $srcstr[$j];
	}
echo $dststr;	
 ?>
</body>
</html>

Open in new window

Author

Commented:
Thanks.  I made a slight correction to your code to prevent:  "Uninitialized string offset:  32"
<?php 

$srcstr = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
$dststr = "";

for($i = 0;$i < 5; $i++) {
         $j = rand(0, strlen($srcstr) - 1);
	$dststr .= $srcstr[$j];
	}
echo $dststr;	

?>

Open in new window

Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
Cool, I'll make a note.  I keep a copy of most of these things.