Hazard Sister
Hazard Sister

Reputation: 1

Php - Random string with fixed regexp

Regarding this:

Generating a unique random string of a certain length and restrictions in PHP?

I want it evolved:

function getRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';

    for ($i = 0; $i < $length; $i++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }

    return $string;
}

How can I do random 8 chars but with 5 digits?

Thanks.

Upvotes: 0

Views: 414

Answers (2)

fusion3k
fusion3k

Reputation: 11689

Your modified function:

function getRandomString( $length = 8 ) 
{
    $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $digits     = '0123456789';
    $string     = '';

    for( $i = 0; $i < 5; $i++ )
    {
        $string .= $digits[ mt_rand( 0, strlen( $digits ) - 1 ) ];
    }

    for( $i = 5; $i < $length; $i++ ) 
    {
        $string .= $characters[ mt_rand( 0, strlen( $characters ) - 1 ) ];
    }

    $array = str_split( $string );
    shuffle( $array );
    return implode( '', $array );
}

3v4l.org demo

Starting from your function, we divide $characters in $characters and $digits, then we add to the empty string 5 random digits and remaining random characters.

At the end, we shuffle resulting string and return it.

Variant (not-repeating characters):

function getRandomString( $length = 8 )
{
    $characters = str_split( 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' );
    $digits     = str_split( '0123456789' );

    shuffle( $characters );
    shuffle( $digits );
    
    $retval = array_merge
    (
        array_slice( $digits, 0, 5 ), 
        array_slice( $characters, 0, $length-5 )
    );
  
    shuffle( $retval );
    
    return implode( '', $retval );
}

We start directly with arrays: $characters and $digits, then we shuffle them, we extract 5 digit items and remaining character items, merging them in $retval array.

At the end, we shuffle $retval array and return it imploded as string.


Edit: precedent version 3 digits / 5 chars; actual version: 5 digits / 3 chars

Upvotes: 0

Isaias
Isaias

Reputation: 1

function getRandomString($length = 8) { $characters = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');

for ($i = 0; $i < $length; $i++) {
    $rand = '';
    foreach (array_rand($characters, 5) as $k) $rand .= $characters[$k];
    $string[$i] = $rand;
}

return $string;

}

http://ideone.com/SSg3m4

Upvotes: 0

Related Questions