2012-01-23 21 views
3

我寫了這個小腳本,它生成一個不錯的隨機密碼。我遇到的問題是,當你打開頁面並選擇全部+將文本複製到剪貼板。即使我使用修剪,結尾處總是有空間。有沒有什麼辦法解決這一問題?選擇全部時,末尾總會有空格

使用Firefox進行測試。

更新:好吧,在用jsfiddle測試後,這與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,Zini'; 

    // 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><?php echo random_readable_pwd(10); ?></body> 
</html> 
+1

沒有修剪。還要確保您的HTML代碼在輸出後不會添加任何空格(這可能取決於您粘貼的瀏覽器,剪貼板和/或文本編輯器)。 – hakre

回答

2

無論你在服務器端是什麼。最後,你會得到這樣的:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head><title></title> 
</head> 
<body>foo</body> 
</html> 

(我添加了一個DOCTYPE,以避免歧義)如果你檢查HTML作爲火狐解釋(你需要的Firebug爲),你會找到這個:

<body>foo </body> 

所以需要生成不同的HTML標記。一種可能性:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head><title></title> 
</head> 
<body> 
    <p>foo</p> 
</body> 
</html> 
+0

我對自己很惱火,這是很容易解決的。 –

+0

另一個解決方案是確保在結束後沒有空白。因此,如果您的來源以'?>'結束並且沒有退貨,問題就不會出現。 –