简体   繁体   中英

Checking for repeated letters in PHP

I am creating a password validation tool, and one of the requirements I'd like is to prevent the user from having too many letters in a row. Any letters, including capital letters, cannot be repeated in a sequence of 3 or more times.

My approach has been to move through the password string with a for loop, and embedding a few checks using regex within that. I can't seem to get the logic to work, and it's probably something simple. Here is one of my (many) failed attempts at cracking this problem:

$seqLetterCounter = 0;
    for($i=0; $i < strlen($password); ++$i) {
            if($password{$i} == '/([a-zA-Z])/') {
                $seqLetterCounter++;
            }
            if($seqLetterCounter > $this->maxSeqLetters){
                $this->errors[6] = 'You have used too many sequential letters in your password.  The maximum allowed is ' . $this->maxSeqLetters . '.';
            }
            if($password{$i} == '/([^a-zA-Z])/') {
                $seqLetterCounter = 0;
            }
        }

$password - a posted value from a form.

$maxSeqLetters - a protected variable that holds an integer value, defined by the user.

errors[] - an array that is used to determine if the password has failed any of the various checks.

Anyone have some pointers?

Fairly simple with a regex:

if (preg_match('/(\w)\1{2,}/', $password)) {
   die("3+ repeated chars not allowed");
}

Search for a character ( \\w ), store it ( () ), then see if that same character comes immediately afterwards ( \\1 ) two or more times {2,} .


ok... so if consecutive sets of 3+ letters or numbers are out, then try

/([a-z]{3,}|[0-9]{3,})/i

for the regex instead. Search for any letters ( [az] ) OR ( | ) numbers ( [0-9] ), which occur 3 or more times ( {3,} ), and do the match in a case-insensitive manner ( i ), so you don't have to worry about aAa breaking the match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM