developer tip

(의사) 임의의 영숫자 문자열 생성

copycodes 2020. 9. 23. 07:44
반응형

(의사) 임의의 영숫자 문자열 생성


PHP에서 'd79jd8c'와 같은 (의사) 임의의 영숫자 문자열을 생성하려면 어떻게해야합니까?


먼저 가능한 모든 문자로 문자열을 만드십시오.

 $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';

range ()사용 하여 더 빨리 할 수도 있습니다 .

그런 다음 루프에서 임의의 숫자를 선택하고 $characters문자열에 대한 인덱스로 사용 하여 임의의 문자를 가져 와서 문자열에 추가합니다.

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

$random_string_length 무작위 문자열의 길이입니다.


나는이 일을 위해이 기능을 좋아한다

function randomKey($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}

echo randomKey(20);

openssl_random_pseudo_bytes 함수를 사용하여 암호화 된 강력한 임의의 (잠재적으로) 8 자 문자열을 생성합니다 .

echo bin2hex(openssl_random_pseudo_bytes(4));

절차 적 방법 :

function randomString(int $length): string
{
    return bin2hex(openssl_random_pseudo_bytes($length));
}

최신 정보:

PHP7은 random_x()더 나은 기능을 도입했습니다 . PHP 5.X에서 온 경우 PHP 7의 random_bytes ()random_int ()에 대한 폴리 필인 우수한 paragonie / random_compat 라이브러리를 사용하십시오 .

function randomString($length)
{
    return bin2hex(random_bytes($length));
}

한 줄 솔루션 :

echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );

문자열에 다른 길이를 설정하기 위해 substr 매개 변수를 변경할 수 있습니다.


ASCII 테이블사용하여 문자 범위를 선택하십시오. 여기서 $ range_start, $ range_end는 ASCII 테이블의 10 진수 열 값입니다.

이 방법은 문자 범위가 다른 문자열 내에서 특별히 정의 된 방법에 비해 더 좋습니다.

// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end   = 122;
$random_string = "";
$random_string_length = 10;

for ($i = 0; $i < $random_string_length; $i++) {
  $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
  // finds the character represented by $ascii_no and adds it to the random string
  // study **chr** function for a better understanding
  $random_string .= chr( $ascii_no );
}

echo $random_string;

더보기:


I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:

    class RandomString
    {
      private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
      private static $string;
      private static $length = 8; //default random string length

      public static function generate($length = null)
      {

        if($length){
          self::$length = $length;
        }

        $characters_length = strlen(self::$characters) - 1;

        for ($i = 0; $i < self::$length; $i++) {
          self::$string .= self::$characters[mt_rand(0, $characters_length)];
        }

        return self::$string;

      }

    }

Maybe I missed something here, but here's a way using the uniqid() function.


I have made the following quick function just to play around with the range() function. It just might help someone sometime.

Function pseudostring($length = 50) {

    // Generate arrays with characters and numbers
    $lowerAlpha = range('a', 'z');
    $upperAlpha = range('A', 'Z');
    $numeric = range('0', '9');

    // Merge the arrays
    $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
    $returnString = "";

    // Add random characters from the created array to a string
    for ($i = 0; $i < $length; $i++) {
        $character = $workArray[rand(0, 61)];
        $returnString .= $character;
    }

    return $returnString;
}

Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.

$str = bin2hex(random_bytes(32));  // 64 character string returned

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();

You can use the following code, copied from this article. It is similar to existing functions except that you can force special character count:

function random_string()
{
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_set_array = array();
    $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
    $character_set_array[] = array('count' => 1, 'characters' => '0123456789');
    $temp_array = array();
    foreach ($character_set_array as $character_set) {
        for ($i = 0; $i < $character_set['count']; $i++) {
            $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        }
    }
    shuffle($temp_array);
    return implode('', $temp_array);
}

If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:

substr( sha1( time() ), 0, 15 )

time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.


This is something I use:

$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);

You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here


Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().

<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
    for($i = 0; $i < 6; $i++) {
        $string .= $character_array[rand(0, (count($character_array) - 1))];
    }
echo $string;
?>

This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().


1 line:

$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;

The modern way to do that with type hint / rand_int for real randomeness

function random_string(int $size): string
{
    $characters = array_merge(
        range(0, 9),
        range('A', 'Z')
    );

    $string = '';
    $max = count($characters) - 1;
    for ($i = 0; $i < $size; $i++) {
        $string .= $characters[random_int(0, $max)];
    }

    return $string;
}

First list the desired characters

$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.

$alpha=substr(str_shuffle($chars), 0, 50);

50 is the Length of string.


public function randomString($length = 8)
{
    $characters = implode([
        'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
        'abcdefghijklmnoprqstuwvxyz',
        '0123456789',
        //'!@#$%^&*?'
    ]);

    $charactersLength = strlen($characters) - 1;
    $string           = '';

    while ($length) {
        $string .= $characters[mt_rand(0, $charactersLength)];
        --$length;
    }

    return $string;
}

참고URL : https://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings

반응형