0

入力したユーザー名が利用できない場合、php でユーザー名を提案する関数を作成したいと考えています。たとえば、入力されたユーザー名が「ビンゴ」で利用できない場合、システムは次のようなユーザー名のリストを提案する必要があります

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

ユーザー名を作成するためのルールは次のとおりです。

  • 最小の長さ 6
  • ユーザー名には最大 3 つの記号を含めることができます (ハイフン、アンダースコアのみ)
  • ユーザー名は英数字で始まり、英数字で終わる必要があります

ヘルプや提案は非常に高く評価されます。ありがとう。

4

3 に答える 3

3

次のコードを試してください:

<?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
)
于 2013-07-04T07:03:36.117 に答える
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;
}
于 2013-07-04T07:04:06.140 に答える
0

PHP と Mysql を確認した後、ユーザーの入力をシャッフルしてユーザーを提案できます。

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

出力:

   bfdcea
   cdfbae
   adefcb
   beacfd
于 2013-07-04T07:48:38.413 に答える