Skip to content

Instantly share code, notes, and snippets.

@kijtra
Created September 6, 2011 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kijtra/1196390 to your computer and use it in GitHub Desktop.
Save kijtra/1196390 to your computer and use it in GitHub Desktop.
[PHP] ランダム文字列の生成
<?php
function random_str($len=12,$special=false){
$len=empty($len) ? 12 : $len;
mt_srand((double)microtime()*1000000);
$chars=array(
array(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
),
array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
),
array(
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
)
);
if($special){
$chars[]=array(
'@', '%', '^', '(', ')', '_', '<', '>', '{', '}', '[', ']',';', '.',
'/', '|', ':', '&', '#', '~', '>', ')', '-', '?', '=', '!', '$', '*'
);
}
$num=count($chars)-1;
$str='';
for($i=0;$i<$len;$i++){
$c=$chars[mt_rand(0,$num)];
$str.=$c[mt_rand(0,count($c)-1)];
}
return $str;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment