Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for repeated letters in PHP

Tags:

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?

like image 562
Patrick Avatar asked Sep 12 '11 19:09

Patrick


1 Answers

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 ([a-z]) 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.

like image 89
Marc B Avatar answered Oct 11 '22 10:10

Marc B