2013-07-04 67 views
0

我想在php中建立一個函數來建議用戶名,如果輸入的用戶名不可用。 例如,輸入的用戶名是「賓果」,它不可用,則系統應提示用戶名列表這樣用戶名建議在PHP

bi_n_go 
go-nbi 
b-n_gio 
b-ng-oi 
... 

規則創建的用戶名是:

  • 最小長度6
  • 用戶名可以包含最多3個符號(僅限連字符,下劃線)
  • 用戶名必須以字母數字開頭並以字母數字結尾

任何幫助和建議將非常可觀。謝謝。

+0

@Deepu:我嘗試str_shuffle與我從一些論壇得到的一些正則表達式,但我無法實現我需要:(你有任何建議..? – LX7

+1

你認爲使用用戶名像'bing_o',''b_ing_o', 'bi_ng_o'將有助於區分它們? – Voitcus

+0

最小長度 - '6',最大 - '3'。大! – vikingmaster

回答

2

嘗試以下代碼:

<?php 
//mutates given user name, producing possibly incorrect username 
function mutate($uname) 
{ 
    $x = str_split($uname); 

    //sort with custom function, that tries to produce only slightly 
    //random user name (as opposed to completely shuffling) 
    uksort($x, function($a, $b) 
    { 
     $chance = mt_rand(0, 3); 
     if ($chance == 0) 
     { 
      return $b - $a; 
     } 
     return $a - $b; 
    }); 

    //insert randomly dashes and underscores 
    //(multiplication for getting more often 0 than 3) 
    $chance = mt_rand(0, 3) * mt_rand(0, 3)/3.; 
    for ($i = 0; $i < $chance; $i ++) 
    { 
     $symbol = mt_rand() & 1 ? '-' : '_'; 
     $pos = mt_rand(0, count($x)); 
     array_splice($x, $pos, 0, $symbol); 
    } 
    return join('', $x); 
} 

//validates the output so you can check whether new user name is correct 
function validate($uname) 
{ 
    //does not start nor end with alphanumeric characters 
    if (!preg_match('/^[a-zA-Z0-9].*[a-zA-Z0-9]$/', $uname)) 
    { 
     return false; 
    } 
    //does contain more than 3 symbols 
    $noSymbols = preg_replace('/[^a-zA-Z0-9]+/', '', $uname); 
    if (strlen($uname) - strlen($noSymbols) > 3) 
    { 
     return false; 
    } 
    //shorter than 6 characters 
    if (strlen($uname) < 6) 
    { 
     return false; 
    } 
    return true; 
} 

實例:

$uname = 'bingo'; 
$desired_num = 5; 
$sug = []; 
while (count($sug) < $desired_num) 
{ 
    $mut = mutate($uname); 
    if (!validate($mut)) 
    { 
     continue; 
    } 
    if (!in_array($mut, $sug) and $mut != $uname) 
    { 
     $sug []= $mut; 
    } 
} 
print_r($sug); 

輸出示例:

Array 
(
    [0] => i-g-obn 
    [1] => bi-gno 
    [2] => bi_ngo 
    [3] => i-bnog 
    [4] => bign-o 
) 
+0

這就是我真正需要的。 Thankyou rr- :) – LX7

1

這是我的創建的函數。 我希望它會幫助你

echo stringGenerator("bingo"); 
function stringGenerator($str) 
{ 
$middleStr = $str."-_"; 
$first = $str[rand(0, strlen($str)-1)]; 
for($i=0;$i<4;$i++) 
{ 
    $middle .= $middleStr[rand(0, strlen($middleStr))]; 
} 
$last = $str[rand(0, strlen($str)-1)]; 

return $first.$middle.$last; 
} 
0

通過PHP和MySQL檢查後,你可以建議用戶通過洗牌用戶的輸入:

$str = 'abcdef'; 
for($i=0;$i<=3;$i++){ 
$shuffled = str_shuffle($str).'</br>'; 
echo $shuffled; 
} 

輸出:

bfdcea 
    cdfbae 
    adefcb 
    beacfd