3

How can I randomly select 5 characters from a given string? They can repeat.

Say my string is this:

static $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";

I just want 5 random characters out of that variable. Thanks to anyone who can help me out!

  • http://stackoverflow.com/questions/6101956/generating-a-random-password-in-php – Damonsson Apr 06 '13 at 05:31
  • It seems [`Random::stringFromAlphabet($chars, $length)`](https://github.com/delight-im/PHP-Random) is exactly what you want. But it also comes with pre-defined alphabets that seem to do what you wanted to achieve, e.g. `Random::alphanumericHumanString($length)`. – caw Nov 23 '19 at 00:12

7 Answers7

3
function gen_code() {

    $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

    return substr(str_shuffle($charset), 0, 5);
}
Wesley Brian Lachenal
  • 4,381
  • 9
  • 48
  • 81
  • This is pretty inefficient in both memory and processing. This causes the entire string to be reordered randomly into a new string, which, depending on the length of the string, can incur significant cost. You only need 5 random characters, yet the shuffling has to generate 62 (technically 61) in the example above. Additionally, the same character can't be chosen twice, which isn't something the question stipulates. – Dan Sep 22 '19 at 13:58
2

Just create 5 random indices and grab the characters from the string:

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

If you simply want to get a 5 character long random string then there are better ways of doing it. Getting random data from the operating system, and then encoding it, would be the ideal way:

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);
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52
2

It's working Please Try it,

<?php
    $length = 5;
    $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    echo $randomString;
?>
Ravi
  • 463
  • 2
  • 11
0

try this

  static $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
  $chars=str_shuffle($chars);
  $finalString=substr($chars, 0,5);
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86
0

Just Pass your $chars into this function and it will return you 5 random characters.

// 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
Dead Man
  • 2,880
  • 23
  • 37
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;

Edit* Had an off by one error, "count($var)" should be "count($var)-1"

MonsterTKE
  • 3
  • 1
  • 4
  • PHP needs to explode that string on every single request. It is unnecessary and easily avoided. Since you are already using a `for` loop you can just as well work with a string, which is must faster and uses less memory. – Sverri M. Olsen Apr 06 '13 at 05:55
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
hakki
  • 6,181
  • 6
  • 62
  • 106