Heim  >  Artikel  >  Backend-Entwicklung  >  生成任意长度字符串的类(自由定制)

生成任意长度字符串的类(自由定制)

WBOY
WBOYOriginal
2016-07-25 08:50:26981Durchsuche
可定制长度、字母、数字、大小写
  1. /*
  2. * 生成随机字符串的类,默认只包含数字、大小写字母
  3. * @author Jerry
  4. */
  5. class randomString {
  6. /*
  7. * 生成的字符串包含的字符设置
  8. */
  9. const NUMERIC_ONLY = 1; //只含有数字
  10. const LETTER_ONLY = 2; //只含有字母
  11. const MIXED = 3; //混合数字和字母
  12. /*
  13. * 用户传入变量,分别为字符串长度;包含的字母;是否包含大写字母
  14. */
  15. protected $length, $type, $upper;
  16. /*
  17. * 参数初始化
  18. * @param int,$length 字符串长度
  19. * @param const,$type 生成字符串的类型
  20. * @param boolean,$upper 是否含有大写字母
  21. */
  22. public function __construct($length = 16, $type = self::MIXED, $upper = true) {
  23. $this->length = $length;
  24. $this->type = $type;
  25. $this->upper = $upper;
  26. }
  27. /*
  28. * 对象被转化为字符串时调用
  29. * @return string
  30. */
  31. public function __toString() {
  32. return $this->pickUpChars();
  33. }
  34. /*
  35. * 生成随机字符串
  36. * @global $type
  37. * @return string,$string
  38. */
  39. public function pickUpChars() {
  40. switch ($this->type) {
  41. case self::NUMERIC_ONLY:
  42. $raw = '0123456789';
  43. break;
  44. case self::LETTER_ONLY:
  45. $raw = 'qwertyuioplkjhgfdsazxcvbnm' .
  46. 'QWERTYUIOPLKJHGFDSAZXCVBNM';
  47. break;
  48. default:
  49. $raw = 'qwertyuioplkjhgfdsazxcvbnm' .
  50. 'QWERTYUIOPLKJHGFDSAZXCVBNM' .
  51. '0123456789';
  52. break;
  53. }
  54. $string = '';
  55. for ($index = 0; $index length; $index++)
  56. $string .= substr($raw, mt_rand(0, strlen($raw) - 1), 1);
  57. if (!$this->upper)
  58. $string = strtolower($string);
  59. return $string;
  60. }
  61. }
  62. //echo new randomString(170, randomString::MIXED, TRUE).'
    ';
复制代码
生成任意长度字符串的类(自由定制)


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn