dre75230
2012-09-11 19:45
浏览 53
已采纳

PHP生成没有特定前缀的随机数?


I want to generate a random 9 character long integer.
I also want to make sure the first 3 digits aren't 814.
This is what I came up with so far:

Function to generate number:

public function randnum(){
$random = substr(number_format(time() * rand(),0,'',''),0,9);
return $random
}


Where I want to get the number at.

$random;
while ((substr(randnum(),0,3)) == '814'){
$random=substr(randnum(),0,3));
}

Is this the right way to ensure the number I get does not start with 814?

图片转代码服务由CSDN问答提供 功能建议


我想生成一个随机的9个字符的长整数。
我也想 确保前3位不是814.
这是我到目前为止所提出的:

生成数字的函数:

  public function randnum(){
 $ random = substr(number_format(time()* rand(),0,'',''),0,9); 
return $ random 
} 
    
 
 


我想在哪里获取数字。

  $ random; 
while((substr)  (randnum(),0,3))=='814'){
 $ random = substr(randnum(),0,3)); 
} 
   
 \  n 

这是确保我获得的数字不是以814开头的正确方法吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duan7664 2012-09-11 19:49
    已采纳
    do {
        $random = mt_rand(100000000, 999999999);
    } while (strpos($random, '814') === 0);
    
    打赏 评论
  • doujing5846 2012-09-11 19:48

    It's a reasonable way to get a number that does not start with 814, but not a reasonable way to get a random number. You shouldn't get time() involved at all, and you should use mt_rand instead of rand.

    You could do it better like this:

    do {
        $random = sprintf("%09d", mt_rand(0, 999999999));
    } while (substr($random, 0, 3) == "814");
    

    If you don't care about the distribution of the generated random numbers (i.e. you are OK with the number being just unpredictable and not really random) and you are going to be generating lots of these, it might make sense to optimize a little:

    do {
        $random = sprintf("%03d", mt_rand(0, 999));
    } while $random == "814";
    
    $random = $random.sprintf("%06d", mt_rand(0, 999999));
    
    打赏 评论
  • duankeng9477 2012-09-11 19:48

    Use preg_match func:

    preg_match("/[^814]/", $str);
    

    Or use

    str_replace("814", "", $str);
    

    Or use

    preg_replace("/^814/", "", $str);

    打赏 评论

相关推荐 更多相似问题