PHP在随机密码脚本中找到拼音

时间:2012-01-28 14:37:48

标签: php

我写过这个随机密码脚本,效果很好。

虽然我想在下面添加额外的行,显示随机密码的字母表字母。

如何实现这一目标的最佳方式?

 <?php
function random_readable_pwd($length=10){

    // the wordlist from which the password gets generated 
    // (change them as you like)
    $words = 'AbbyMallard,AbigailGabble,AbisMal,Abu,Adella,TheAgent,AgentWendyPleakley,Akela,AltheAlligator';

    $phonetic = array("a"=>"alfa","b"=>"bravo","c"=>"charlie","d"=>"delta","e"=>"echo","f"=>"foxtrot","g"=>"golf","h"=>"hotel","i"=>"india","j"=>"juliett","k"=>"kilo","l"=>"lima","m"=>"mike","n"=>"november","o"=>"oscar","p"=>"papa","q"=>"quebec","r"=>"romeo","s"=>"sierra","t"=>"tango","u"=>"uniform","v"=>"victor","w"=>"whisky","x"=>"x-ray","y"=>"yankee","z"=>"zulu");

   // Split by ",":
    $words = explode(',', $words);
    if (count($words) == 0){ die('Wordlist is empty!'); }

    // Add words while password is smaller than the given length
    $pwd = '';
    while (strlen($pwd) < $length){
        $r = mt_rand(0, count($words)-1);
        $pwd .= $words[$r];
    }

    $num = mt_rand(1, 99);
     if ($length > 2){
        $pwd = substr($pwd,0,$length-strlen($num)).$num;
    } else { 
        $pwd = substr($pwd, 0, $length);
    }

   $pass_length = strlen($pwd);
   $random_position = rand(0,$pass_length);

   $syms = "!@#%^*()-?";
   $int = rand(0,9);
   $rand_char = $syms[$int];

   $pwd = substr_replace($pwd, $rand_char, $random_position, 0);

    return $pwd;
}
?>
<html><head><title>Password generator</title></head>
<body><p><?php echo random_readable_pwd(10); ?></p></body>
</html>

E.g输出:

替代!heAll87

ALFA lima tango!酒店echo ALFA lima lima 8 7

1 个答案:

答案 0 :(得分:3)

您应该逐个字符地循环生成的密码,并以此方式构建一个拼音字符串。

例如(根据您的代码和需求进行自定义,底部示例尚未经过测试,但应该让您了解如何处理它):

$password = "aBcDefG";
$phonetics = array("a"=>"alfa","b"=>"bravo","c"=>"charlie","d"=>"delta","e"=>"echo","f"=>"foxtrot","g"=>"golf","h"=>"hotel","i"=>"india","j"=>"juliett","k"=>"kilo","l"=>"lima","m"=>"mike","n"=>"november","o"=>"oscar","p"=>"papa","q"=>"quebec","r"=>"romeo","s"=>"sierra","t"=>"tango","u"=>"uniform","v"=>"victor","w"=>"whisky","x"=>"x-ray","y"=>"yankee","z"=>"zulu");
$phonetic = array();
for ($i = 0; $i < strlen($password); $i++) {
    $char = substr($password, $i, 1);
    $phonetic[] = (ctype_upper($char) ? strtoupper(strtr(strtolower($char), $phonetics)) : strtolower(strtr($char, $phonetics)));
}
$phonetic = join(' ', $phonetic);
echo $phonetic;

编辑我的代码有问题,我更新并测试了它。输出是:alfa BRAVO charlie DELTA echo foxtrot GOLF