PHP產生隨機字元方法

來源:互聯網
上載者:User

通常情況下,當我們要產生一個隨機字串時,總是先建立一個字元池,然後用一個迴圈和mt_rand()或rand()產生php隨機數,從字元池中隨機選取字元,最後拼湊出需要的長度。
(轉)

  1. function randomkeys($length)
  2. {
  3.     $pattern = '1234567890abcdefghijklmnopqrstuvwxyz
  4.                 ABCDEFGHIJKLOMNOPQRSTUVWXYZ,./&l
  5.                 t;>?;#:@~[]{}-_=+)(*&^%$£"!';    //字元池
  6.     for($i=0;$i<$length;$i++)
  7.     {
  8.         $key .= $pattern{mt_rand(0,35)};    //產生php隨機數
  9.     }
  10.     return $key;
  11. }
  12. echo randomkeys(8);

這個php隨機函數能產生XC*=z~7L這樣的字串,夠隨機!

現在介紹另一種用PHP產生隨機數的方法:利用chr()函數,省去建立字元池的步驟。

  1. function randomkeys($length)
  2. {
  3.     $output='';
  4.     for ($a = 0; $a < $length; $a++) {
  5.         $output .= chr(mt_rand(33, 126));    //產生php隨機數
  6.     }
  7.     return $output;
  8. }
  9. echo randomkeys(8);

在第二個php隨機函數裡,先用mt_rand()產生一個介於33到126之間的php隨機數,然後用chr()函數轉化成字元。查看ascii碼錶就會發現,33到126代表的正是第一個函數中字元池裡的所有字元。第二個函數和第一個函數功能相同,而且更簡潔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.