note 74296 deleted from function.rand by nlopess
| From: | nlopess@php.net | Date: | Wed, 04 Apr 2007 13:36:23 +0000 |
| Subject: | note 74296 deleted from function.rand by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-125087@lists.php.net to get a copy of this message | ||
Note Submitter: vzeman at qualityunit dot com
----
A lot of developers need to generate random id
depending on any format defined by e.g. any config switch.
Here is example of function,
which will generate random id depending on specified format
/**
* Generates random string depending on format
* Z - represents any character between A-Z
* X - represents characters 0-9, a-z, A-Z
* z - represents any character between a-z
* 9 - represents any number between 0-9
* all other characters are used as in format
*/
function getRandomString($format='ZZZZZZ-99999') {
$chars_Z = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$chars_z = str_shuffle('abcdefghijklmnopqrstuvwzxy');
$chars_9 = str_shuffle('1234567890');
$chars_X = $chars_Z . $chars_z . $chars_9;
$result = '';
for ($i = 0; $i < strlen($format); $i++) {
switch($format[$i]) {
case 'X':
$result .= $chars_X[rand(0,strlen($chars_X)-1)];
break;
case 'Z':
$result .= $chars_Z[rand(0,strlen($chars_Z)-1)];
break;
case 'z':
$result .= $chars_z[rand(0,strlen($chars_z)-1)];
break;
case '9':
$result .= $chars_9[rand(0,strlen($chars_9)-1)];
break;
default:
$result .= $format[$i];
break;
}
}
return $result;
}
We used this function e.g. in helpdesk software,
which we develop (www.qualityunit.com/supportcenter/) for generating of ticket ids