Reputation: 3185
I would like to create a random ID like an airline ticket with out any zeros, o's, ones's, or L's. It would be nice if server time was used in the generation process so no two IDs will be the same. How would one do this?
Upvotes: 1
Views: 792
Reputation: 4472
Another option
function genGoodRandString() {
$rnd_id = md5(uniqid(rand(), true)); // get long random id
$bad = array('0','o','1','l','8'); // define bad chars
$fixed = str_replace($bad, '', $rnd_id); // fix
return substr($fixed, 0, 10); // cut to required length
}
Upvotes: 0
Reputation: 298106
Following the awesome PHP naming scheme:
function generate_airline_ticket_number($length) {
$characters = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
$max = strlen($characters) - 1;
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
return $string;
}
I should submit this to be included into PHP6 ;)
If you're worried about collisions, my approach would be to do an endless loop:
do
{
$random_stuff = generate_airline_ticket_number(10);
} while(check_if_string__is_not_in__the_database($random_stuff));
Upvotes: 8
Reputation: 3722
uniqid()
seems perfect, apart from your limitations on letters and numbers. Selecting a great font may mitigate some of your needs, so you have L, a zero with a strike through, etc.
Baring that, you haven't placed any other limitations so what about.
$id = uniqid()
$bad = array("0", "o", "l", "1");
$good = array("-", "#", "&", "$");
$id_clean = str_replace($bad, $good, $id);
The power of uniqid() combined with easily identified characters.
Upvotes: 0
Reputation: 236
Why not just use a hash like MD5? I believe PHP has a md5() function built in. Another good one to use is sha1().
Using both of these hash functions you will end up getting what you don't want so I suggest you run a regex pattern on the hash to replace them with a random letter A-Z.
Oh, and hashes are usually 100% unique.
I guess I learned something new today.
Upvotes: -2
Reputation: 152206
There is always possibility that generated number will be repeated.
You have to store that generated earlier numbers and always check if currently generated number does not exist.
To generate a random number you can just use int rand ( int $min , int $max )
Upvotes: 0