简体   繁体   English

在PHP中检查重复的字母

[英]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. 任何字母,包括大写字母,都不能以3次或更多次的顺序重复。

My approach has been to move through the password string with a for loop, and embedding a few checks using regex within that. 我的方法是使用for循环移动密码字符串,并在其中使用正则表达式嵌入一些检查。 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. $ password - 表单中的已发布值。

$maxSeqLetters - a protected variable that holds an integer value, defined by the user. $ maxSeqLetters - 一个受保护的变量,它包含一个由用户定义的整数值。

errors[] - an array that is used to determine if the password has failed any of the various checks. errors [] - 一个数组,用于确定密码是否已通过各种检查失败。

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,} . 搜索一个字符( \\w ),存储它( () ),然后查看相同的字符是否在之后立即出现( \\1 )两次或更多次{2,}


ok... so if consecutive sets of 3+ letters or numbers are out, then try 好的...所以,如果连续的3个以上的字母或数字组合出来,那就试试吧

/([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. 搜索任何字母( [az] )OR( | )数字( [0-9] ),它们出现3次或更多次( {3,} ),并以不区分大小写的方式进行匹配( i ),所以你不必担心aAa打破比赛。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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