2012-01-28 33 views
0

我已经写了这个随机的密码脚本,它完美的工作。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 = "[email protected]#%^*()-?"; 
    $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输出:

Alt键heAll87

ALFA利马探戈!酒店回声ALFA利马利马8 7

回答

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

+0

谢谢,我明白我需要循环使用字符串长度的每个字符。我无法弄清楚的难点在于替换拼音数组和测试案例。 – 2012-01-28 15:12:34

+0

@JohnMagnolia查看我的编辑! :) – 2012-01-28 15:21:24

+0

第一次工作出色,谢谢。我看到你在substr中使用$ i的方式来查明每个字符。 – 2012-01-28 15:32:22