PHP实现生成任意长度字符串

PHP实现生成任意长度字符串,可定制长度、字母、数字、大小写。具体代码如下:

 

<?
 
/*
* 生成随机字符串的类,默认只包含数字、大小写字母
* @author Jerry <maolyc@gmail.com>
*/
 
class randomString {
    /*
     * 生成的字符串包含的字符设置
     */
 
    const NUMERIC_ONLY = 1; //只含有数字
    const LETTER_ONLY = 2; //只含有字母
    const MIXED = 3; //混合数字和字母
 
    /*
     * 用户传入变量,分别为字符串长度;包含的字母;是否包含大写字母
     */
 
    protected $length, $type, $upper;
 
    /*
     * 参数初始化
     * @param int,$length 字符串长度
     * @param const,$type 生成字符串的类型
     * @param boolean,$upper 是否含有大写字母
     */
 
    public function __construct($length = 16, $type = self::MIXED, $upper = true) {
        $this->length = $length;
        $this->type = $type;
        $this->upper = $upper;
    }
 
    /*
     * 对象被转化为字符串时调用
     * @return string
     */
 
    public function __toString() {
        return $this->pickUpChars();
    }
 
    /*
     * 生成随机字符串
     * @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).'<br/>';   转载请注明来源论文发表 http://www.400qikan.com

转载于:https://www.cnblogs.com/ryry/p/3205268.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值