Forum Moderators: coopster
Well I trawled the web looking at tutorials and exapmles, but I just can't find the answer!
I want to search a string for consecutive repeated characters, but can't figure out how to do it!
In these examples both have 3 characters repeated 3 times, but I want to differentiate between abcabcabc and aaabbbccc, and look for the repeated occurence, i.e i am looking for aaa or bbb or ccc
This seems to find any string where a-z is repeated more than once which is not what I need: "/[az]{2}/"
Any ideas?
Thanx
Crankshaft
I would try something like this:
<?phpfunction repchars($string, $repeated)
{
$string = strtolower($string);
for($i = 0; $i < strlen($string); $i++)
{
for($j = 0; $j < $repeated; $j++)
{
$index = $i+$j;
if($string[$i] === $string[$index]) {
$found++;
}
else { $found = 0; }
}
if($found == $repeated) {
$rep = substr($string, $i, $repeated);
break;
}
else { $j=0; }
}
if($rep) { return $rep; }
else { return "No Repetition"; }
}
print repchars("aaabbbccc", 3)."<br>"; //produces 'aaa'
print repchars("aabbbccc", 3)."<br>"; //produces 'bbb'
print repchars("aabbcc", 3).<br>"; //produces 'No Repetition'
?>
Hope this helps...
Btw, the function format is: repchars(text, how many reps you are looking for)
It returns the first substring that has the amount of reps you specify.
eelix