3

如何从给定的字符串中随机选择 5 个字符?他们可以重复。

说我的字符串是这样的:

static $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";

我只想从该变量中取出 5 个随机字符。感谢任何可以帮助我的人!

4

7 回答 7

3
function gen_code() {

    $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

    return substr(str_shuffle($charset), 0, 5);
}
于 2013-04-06T05:33:31.493 回答
2

只需创建 5 个随机索引并从字符串中获取字符:

$chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
$length = strlen($chars) - 1;
$randchars = '';
for ($i = 0; $i < 5; $i++) {
    $position = mt_rand(0, $length);
    $randchars .= $chars[$position];
}
echo $randchars;

如果您只是想获得一个 5 字符长的随机字符串,那么有更好的方法可以做到这一点。从操作系统获取随机数据,然后对其进行编码,将是理想的方式:

function random_string($length) {
    $raw   = (int) ($length * 3 / 4 + 1);
    $bytes = mcrypt_create_iv($raw, MCRYPT_DEV_URANDOM);
    $rand  = str_replace('+', '.', base64_encode($bytes));
    return substr($rand, 0, $length);
}
echo random_string(5);
于 2013-04-06T05:36:20.477 回答
2

它的工作,请尝试它,

<?php
    $length = 5;
    $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    echo $randomString;
?>
于 2013-04-06T05:40:00.713 回答
0

尝试这个

  static $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
  $chars=str_shuffle($chars);
  $finalString=substr($chars, 0,5);
于 2013-04-06T05:32:37.757 回答
0

只需将您$chars传入此函数,它将返回 5 个随机字符。

// to generate random string

function rand_str($length = 5, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    // Length of character list
    $chars_length = (strlen($chars) - 1);
    // Start our string
    $string = $chars{rand(0, $chars_length)};
    // Generate random string
    for ($i = 1; $i < $length; $i = strlen($string))
    {
        // Grab a random character from our list
        $r = $chars{rand(0, $chars_length)};
       // Make sure the same two characters don't appear next to each other
       if ($r != $string{$i - 1}) $string .=  $r;
    }
    // Return the string
    return $string;
}

// function ends here
于 2013-04-06T05:33:40.497 回答
0
$var = explode(',' , '1,2,3,4,5,6,7,8,9,a,b,c,d,f,g,h,j,k,m,n,p,q,r,s,t,v,w,x,y,z,B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z');
$string ='';
for($i=0; $i <= 4; $i++)
{
    $string .= $var[rand(0, count($var)-1)];
}


echo $string;

编辑*有一个错误,“count($var)”应该是“count($var)-1”

于 2013-04-06T05:45:27.160 回答
0
//define a function    
function generateRandomString($length = 5){
    $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return substr(str_shuffle($chars),0,$length);
}

//usage
echo generateRandomString(5); //random string legth: 5
echo generateRandomString(6); //random string legth: 6
echo generateRandomString(7); //random string legth: 7
于 2019-05-13T12:26:47.710 回答