精易论坛

标题: 请PHP大神帮忙 [打印本页]

作者: liu307921917    时间: 2021-6-16 18:02
标题: 请PHP大神帮忙
function getcode(){
        $str = null;  
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
        $max = strlen($strPol)-1;  
        for($i=0;$i<20;$i++){
                $str.=$strPol[rand(0,$max)];
        }  
        return $str;
}

以上代码能返回一个随机的20位字符,例如:JEM2DMR3SZRWY6F1R4ZD


想请大神如何能将返回的字符进行每4个字符加"-"进行分割
需要的结果:JEM2-DMR3-SZRW-Y6F1-R4ZD


作者: liu307921917    时间: 2021-6-16 18:24
谢谢!
已经解决了

19行改
$str.= $i%4 == 0 && $i>0 ? '-'.$strPol[rand(0,$max)] : $strPol[rand(0,$max)];
作者: 深爱者    时间: 2021-6-16 19:16
恭喜解决了,币可以赏我嘛
作者: 花老板    时间: 2021-6-16 20:20
要不也写一个  rand的(0,1)随机数
作者: KServer    时间: 2021-7-10 04:26
  1. function getcode(){
  2.         $str = null;  
  3.         $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
  4.         $max = strlen($strPol)-1;  
  5.         for($i=0;$i<20;$i++){
  6.                 $str.=$strPol[rand(0,$max)];
  7.         }  
  8.         return chunk_split($str, 4, '-');
  9. }
复制代码


方便快捷好看

作者: hadisi    时间: 2022-6-20 20:45
深爱者 发表于 2021-6-16 19:16
恭喜解决了,币可以赏我嘛

你咋做到的,2精币




欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4