I'm writing a password strength checker in PHP, and I'm using Regular Expressions to calculate various parameters for the strength calculation. I need to be able to check the number of repeating consecutive characters in a string. For example:
baaabaaablacksheep
would return 5
sillystring
would return 1
and so on...
You can use regex with \1+
to find the repeating characters, and then use strlen()
to count them. Try something like:
$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) . "
";
}
}
Output:
aaa = 3
aaa = 3
ee = 2
Another variant of the solution posted by 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
", $p, $repeats);
}
prints:
baaabaaablacksheep => 5 repeats
okstring => 0 repeats
sillystring => 1 repeats