3

我正在尝试创建一个应该包含 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

4 回答 4

1

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

于 2012-06-21T10:55:17.507 回答
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");

?>
于 2012-06-21T11:50:01.823 回答
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 );
}
于 2012-06-21T11:26:51.687 回答
0

尝试这个 :

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

这显示

A
length:1

尝试\从您的列表中删除。

于 2012-06-21T11:17:24.317 回答