class GenRandWords { private static $_alphas = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ]; // 生成 private $_num = 1; // 单词最小长度 private $_minLength = 5; // 单词最大长度 private $_maxLength = 20; public function __construct($config = []) { if (isset($config['num']) && $config['num'] > 0) { $this->_num = $config['num']; } if (isset($config['minLength']) && $config['minLength'] > 0) { $this->_minLength = $config['minLength']; } if (isset($config['maxLength']) && $config['maxLength'] > 0) { $this->_maxLength = $config['maxLength']; } } public function generate() { $words = []; $num = $this->_num; while ($num--) { $words[] = $this->_genOneWord(); } return $words; } private function _genOneWord() { $word = ''; $wordLength = mt_rand($this->_minLength, $this->_maxLength); while ($wordLength--) { $index = mt_rand(0, 25); $word .= self::$_alphas[$index]; } return $word; } }
用法:
$config = [ 'num' => 100, ]; $genRandWords = new GenRandWords($config); $words = $genRandWords->generate();