Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function to create 8 chars long hash ([a-z] = no numbers allowed)

Tags:

php

hash

I need PHP function that will create 8 chars long [a-z] hash from any input string. So e.g. when I'll submit "Stack Overflow" it will return e.g. "gdqreaxc" (8 chars [a-z] no numbers allowed)

like image 320
chubbyk Avatar asked Jul 07 '10 18:07

chubbyk


2 Answers

Perhaps something like:

$hash = substr(strtolower(preg_replace('/[0-9_\/]+/','',base64_encode(sha1($input)))),0,8);

This produces a SHA1 hash, base-64 encodes it (giving us the full alphabet), removes non-alpha chars, lowercases it, and truncates it.

For $input = 'yar!';:

mwinzewn

For $input = 'yar!!';:

yzzhzwjj

So the spread seems pretty good.

like image 130
Lucas Oman Avatar answered Nov 04 '22 21:11

Lucas Oman


This function will generate a hash containing evenly distributed characters [a-z]:

function my_hash($string, $length = 8) {

    // Convert to a string which may contain only characters [0-9a-p]
    $hash = base_convert(md5($string), 16, 26);

    // Get part of the string
    $hash = substr($hash, -$length);

    // In rare cases it will be too short, add zeroes
    $hash = str_pad($hash, $length, '0', STR_PAD_LEFT);

    // Convert character set from [0-9a-p] to [a-z]
    $hash = strtr($hash, '0123456789', 'qrstuvwxyz');

    return $hash;
}

By the way, if this is important for you, for 100,000 different strings you'll have ~2% chance of hash collision (for a 8 chars long hash), and for a million of strings this chance rises up to ~90%, if my math is correct.

like image 26
Alexander Konstantinov Avatar answered Nov 04 '22 23:11

Alexander Konstantinov