Home  >  Article  >  Backend Development  >  Class for generating strings of arbitrary length (free customization)

Class for generating strings of arbitrary length (free customization)

WBOY
WBOYOriginal
2016-07-25 08:50:26980browse
Customizable length, letters, numbers, upper and lower case
  1. /*
  2. * Class for generating random strings, which only contains numbers and uppercase and lowercase letters by default
  3. * @author Jerry
  4. */
  5. class randomString {
  6. /*
  7. * Character settings contained in the generated string
  8. */
  9. const NUMERIC_ONLY = 1; //Only contains numbers
  10. const LETTER_ONLY = 2; //Only contains letters
  11. const MIXED = 3; //Mix numbers and letters
  12. /*
  13. * The variables passed in by the user are the length of the string; the letters it contains; whether it contains uppercase letters
  14. */
  15. protected $length, $type, $upper;
  16. /*
  17. * Parameter initialization
  18. * @param int,$length The length of the string
  19. * @param const,$type The type of the generated string
  20. * @param boolean,$upper Whether it contains uppercase letters
  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. * Called when the object is converted to a string
  29. * @return string
  30. */
  31. public function __toString() {
  32. return $this->pickUpChars();
  33. }
  34. /*
  35. * Generate a random string
  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 < $this->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).'
    ';
Copy code
Class for generating strings of arbitrary length (free customization)


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn