0

これが私の最初の質問です。現在、私は PHP フォーラム スクリプトを開発しており、人々が私のルールに従ってユーザー名を登録できるようにしたいと考えています。

ルールは簡単です:

  • 最初の文字は文字でなければなりません
  • 数字も使用できますが、最初ではありません
  • フルストップ/アンダースコアを 1 回使用できますが、ユーザー名の末尾には使用できません

関数を書き留めて助けてください。いくつかのチュートリアルを読みましたが、正規表現がよくわかりません。そして、このため、私は立ち往生しています。ご回答ありがとうございます。

20分後に追加:

回答ありがとうございます。もう 1 つ質問があります。EG aaa123, ab-cd,uuuu...どのように?

4

4 に答える 4

0

次のパターンでは、4 ~ 12 文字のユーザー名を使用できます。最初の文字は文字で、ドットとアンダースコアは 1 つだけです。

$pattern = '~^(?=.{4,12}$)[a-z]++[^\W_]*+(_[^\W_]++)?+(?>\.[^\W_]++)?+(?(1)|(_[^\W_]++)?+)$~i';

preg_match と一緒に使用して、ユーザー名を確認できます。

パターン詳細:

~                # pattern delimiter
^                # begining anchor
(?=.{4,12}$)     # lookahead assertion: check if the length is between 4 and 12
                 # characters. It stand for: "followed by between 4 and 12 chars
                 # and the end of the string
[a-z]++          # one or more letters
[^\W_]*+         # zero or more letters or digits. Since ^ means that the character
                 # class is negated, _ is excluded with all that is not a part of \w
(_[^\W_]++)?+    # first capturing group with an underscore and one or more
                 # letters/digits. The group is optional
(?>\.[^\W_]++)?+ # a non capturing group with a dot (optional too)
(?(1)            # conditional: if the first capturing group exist there is nothing
     |           # OR
   (_[^\W_]++)?+ # you can have an underscore here (optional)
)
$                # anchor: end of the string
~                # pattern delimiter
i                # case insensitive modifier

「ダムユーザー名」については、「ブラックリスト」を作成して後で(または先読みまたは後読みのパターンで)ユーザー名を確認する以外にできることはあまりありませんが、そうではないため、これが非常に役立つかどうかはわかりませんパスワード。

于 2013-08-12T03:34:26.710 に答える
0

あなたが正規表現を要求したことは知っていますが、昔ながらの方法で非常に簡単に実行できることを納得できるかもしれません。

function validUsername($user) {

    // A few variables
    $minlen = 3;
    $maxlen = 20;
    $usrlen = strlen($user);

    // Allowed length of username
    if ($usrlen < $minlen || $usrlen > $maxlen) {
        return false;
    }
    // First character must be alpha
    if ( ! ctype_alpha($user[0])) {
        return false;
    }
    // Last letter cannot be . or _ which means
    // that it must be alphanum
    if ( ! ctype_alnum($user[$usrlen-1])) {
        return false;
    }
    // Go over each character, excluding the first
    // and last, because we have already dealt with them
    for ($i = 1; $i < $usrlen-1; $i++) {

        // Grab the currect character
        $char = $user[$i];

        // If it is alphanum then it is valid
        if (ctype_alnum($char)) {
            continue;
        }
        // Dots and underscores cannot appear in pairs
        elseif ($char === '.' || $char === '_') {
            if ($user[$i-1] === $char || $user[$i+1] === $char) {
                return false;
            }
        }
        // Character not supported
        else return false;
    }
    // Everything seems to be in order
    return true;
}
于 2013-08-12T03:49:19.317 に答える