1

我正在用 PHP 编写密码强度检查器,并且正在使用正则表达式来计算强度计算的各种参数。我需要能够检查字符串中重复连续字符的数量。例如:

baaabaaablacksheep会回来5

sillystring会回来1

and so on...
4

2 回答 2

4

您可以使用 regex with\1+来查找重复字符,然后使用strlen()来计算它们。尝试类似:

$str = 'baaabaaablacksheep';    
$repeating = array();
preg_match_all('/(\w)(\1+)/', $str, $repeating);

if (count($repeating[0]) > 0) {
    // there are repeating characters
    foreach ($repeating[0] as $repeat) {
        echo $repeat . ' = ' . strlen($repeat) . "\n";
    }
}

输出:

aaa = 3
aaa = 3
ee = 2
于 2012-07-24T15:41:34.977 回答
1

newfurniturey发布的解决方案的另一个变体:

$passarr = Array('baaabaaablacksheep', 'okstring', 'sillystring');

foreach($passarr as $p) {
   $repeats = 0;
   preg_match_all('/(.)(\1+)/', $p, $matches, PREG_SET_ORDER);
   foreach($matches as $m) $repeats += strlen($m[2]);
   printf("%s => %d repeats\n", $p, $repeats);
}

印刷:

baaabaaablacksheep => 5 repeats
okstring => 0 repeats
sillystring => 1 repeats
于 2012-07-24T16:34:13.170 回答