Created
March 11, 2010 15:00
-
-
Save nissuk/329204 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* ランダムな文字列を返します。 | |
* | |
* 使用例: | |
* randomstr(); | |
* randomstr(6, array('unique'=>true, 'chars'=>'abcdef')); | |
* randomstr(6, array('unique'=>true, 'chars'=>range('c', 'h'))); | |
* | |
* オプション: | |
* - bool 'unique' - 返される各文字を重複させない(true)かさせる(false)か。既定値はfalse | |
* - mixed 'chars' - 使用する文字の候補(stringかarray)。既定値はa~z, A~Z, 0~9 | |
* | |
* @param int $length 返される文字列の長さ | |
* @param array $options オプション | |
* @return string ランダム文字列 | |
*/ | |
function randomstr($length=6, array $options=array()) { | |
$unique = isset($options['unique']) | |
? $options['unique'] : false; | |
$chars = isset($options['chars']) | |
? $options['chars'] : array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9')); | |
if (is_string($chars)) { | |
$chars = preg_split('//', $chars, -1, PREG_SPLIT_NO_EMPTY); | |
} | |
$result = ''; | |
$count = count($chars); | |
for ($i = 0; $i < $length; $i++) { | |
$index = mt_rand(0, $count - 1); | |
$result .= $chars[$index]; | |
if ($unique) { | |
array_splice($chars, $index, 1); | |
$count -= 1; | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment