我正在用PHP编写密码强度检查器,我正在使用正则表达式来计算强度计算的各种参数。我需要能够检查字符串中重复连续字符的数量。例如:
baaabaaablacksheep
会返回5
sillystring
会返回1
and so on...
答案 0 :(得分:4)
您可以使用\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
答案 1 :(得分: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