在php中创建30个字符的随机字符串

时间:2012-06-21 10:50:56

标签: php random

我正在尝试创建一个应该包含30个字符的随机字符串。但有时它也创造了28个字符。如何解决这个问题? 我的代码就像:

function random_string(){
    $character_set_array = array( );
    $character_set_array[ ] = array( 'count' => 15, 'characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ' );
    $character_set_array[ ] = array( 'count' => 6, 'characters' => '0123456789' );
    $character_set_array[ ] = array( 'count' => 9, 'characters' => '!@#$%^&+_|~-=\{}[]:?/' );
    $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 );
}

请帮帮我。

4 个答案:

答案 0 :(得分:1)

我执行了10.000次函数,但从未得到一个少于30个字符的字符串。

答案 1 :(得分:1)

我无法帮助改写这个功能。否则我就无法入睡......

<?php

function random_string(){

        $charset = array();

        $charset[]='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
        $charset[]='0123456789';
        $charset[]='!@#$%^&+_|~-=\{}[]:?/';

        $res='';

        for($i=0;$i<30;$i++){
                $j=$charset[array_rand($charset)];
                $res.=$j[mt_rand(0,strlen($j)-1)];
        }

        return($res);
}

// Let us do a long test that the returned random string is always 30 characters long
for($a=0;$a<1000000;$a++){
        $z=random_string();
        if(strlen($z)!=30){print("ERR!!! --> $z");exit;}
}

// If we make it here then all is good... probably.
print("OK!\n");

?>

答案 2 :(得分:0)

试试这个:

$temp_array = array( );
$temp_array[] = '\';
$temp_array[] = 'A';
echo implode( '', $temp_array );
echo '<br>length:'.strlen( implode( '', $temp_array ));

显示

A
length:1

尝试从列表中删除\

答案 3 :(得分:0)

试试这个:

function random_string(){
    $character_set_array = array( );
    $character_set_array[ ] = array( 'count' => 15, 'characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ' );
    $character_set_array[ ] = array( 'count' => 6, 'characters' => '0123456789' );
    $character_set_array[ ] = array( 'count' => 9, 'characters' => '!@#$%^&+_|~-=\{}[]:?/' );
    $temp_array = array( );

    foreach ( $character_set_array as $character_set )
    {
      for ( $i = 0; $i < $character_set[ 'count' ]; $i++ )
      {
        $temp_array[ ] = substr($character_set[ 'characters' ], 0, rand(0, count( $character_set[ 'characters' ] ) - 1 ));
      }
    }

    shuffle( $temp_array );
    return implode( '', $temp_array );
}