Customizable length, letters, numbers, upper and lower case
- /*
- * Class for generating random strings, which only contains numbers and uppercase and lowercase letters by default
- * @author Jerry
- */
-
- class randomString {
- /*
- * Character settings contained in the generated string
- */
-
- const NUMERIC_ONLY = 1; //Only contains numbers
- const LETTER_ONLY = 2; //Only contains letters
- const MIXED = 3; //Mix numbers and letters
-
- /*
- * The variables passed in by the user are the length of the string; the letters it contains; whether it contains uppercase letters
- */
-
- protected $length, $type, $upper;
-
- /*
- * Parameter initialization
- * @param int,$length The length of the string
- * @param const,$type The type of the generated string
- * @param boolean,$upper Whether it contains uppercase letters
- */
-
- public function __construct($length = 16, $type = self::MIXED, $upper = true) {
- $this->length = $length;
- $this->type = $type;
- $this->upper = $upper;
- }
-
- / *
- * Called when the object is converted to a string
- * @return string
- */
-
- public function __toString() {
- return $this->pickUpChars();
- }
-
- /*
- * Generate a random string
- * @global $type
- * @return string,$string
- */
-
- public function pickUpChars() {
- switch ($this->type) {
- case self::NUMERIC_ONLY:
- $raw = '0123456789' ;
- break;
- case self::LETTER_ONLY:
- $raw = 'qwertyuioplkjhgfdsazxcvbnm' .
- 'QWERTYUIOPLKJHGFDSAZXCVBNM';
- break;
-
- default:
- $raw = 'qwertyuioplkjhgfdsazxcvbnm' .
- 'QWERTYUIOPLKJHGFDSAZXCVBNM' .
- '0123456789';
- break;
- }
- $string = '';
- for ($index = 0; $index < $this->length; $index++)
- $string .= substr($raw, mt_rand(0, strlen($ raw) - 1), 1);
- if (!$this->upper)
- $string = strtolower($string);
- return $string;
- }
-
- }
-
- //echo new randomString(170, randomString::MIXED, TRUE).'
';
-
-
-
Copy code
|