PHP generate a unique string

2019-04-09 12:13发布

I have an ID column in a table which stores the row ID number (auto increment), For example 1, 2, 3. I want to generated a random and unique string which could contain only numbers, alphabets and dash (-) and underscore (_). The length of string should be 4-6, and it should be unique. Can someone help me how to generate? thanks.

3条回答
Viruses.
2楼-- · 2019-04-09 12:27

Use this - base_convert(mt_rand(0x1D39D3E06400000, 0x41C21CB8E0FFFFFF), 10, 36), but check new value against db.

查看更多
唯我独甜
3楼-- · 2019-04-09 12:44

Try this

function genRandomString($length) {
   $characters = ’0123456789abcdefghijklmnopqrstuvwxyz-_’;
   $string = ”;    
   for ($p = 0; $p < $length; $p++) {
      $string .= $characters[mt_rand(0, strlen($characters))];
    }
   return $string;
}

Call the function with the length you want

查看更多
小情绪 Triste *
4楼-- · 2019-04-09 12:46
function random_gen($length)
{
  $random= "";
  srand((double)microtime()*1000000);
  $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $char_list .= "abcdefghijklmnopqrstuvwxyz";
  $char_list .= "1234567890-_";
  // Add the special characters to $char_list if needed

  for($i = 0; $i < $length; $i++)
  {
    $random .= substr($char_list,(rand()%(strlen($char_list))), 1);
  }
  return $random;
}

$random_string = random_gen(6); //This will return a random 6 character string

Above function will generate the unique string

查看更多
登录 后发表回答