-1

I have no idea how to create function which counts how many times 3 the same letters in a row reapets in one string?

For example: avcdddjrg return 1, aaargthbbb return 2

I can detect if there are 3 the same characters in a row, but can't figure it out how to count it

$input = 'hellooommm'; 
  if (preg_match('/(.)\1{2}/', $input)) {
    return 1;
  }else {
    return 0;
  }

Thank you

kales
  • 63
  • 4
  • 3
    Welcome to [so]! At this site you are expected to try to **write the code yourself**. After **[doing more research](//meta.stackoverflow.com/questions/261592)** if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working** and providing a [**Minimal, Complete, and Verifiable example**](//stackoverflow.com/help/mcve). I suggest reading [ask] a good question and [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Also, be sure to take the [tour] and read **[this](//meta.stackoverflow.com/questions/347937/)**. – John Conde Jun 02 '17 at 12:25
  • you can use regular expressions - look at this for a starting point https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times – MikO Jun 02 '17 at 12:32
  • Also check this answer https://stackoverflow.com/questions/25773605/determine-repeat-characters-in-a-php-string – Manikandan Jun 02 '17 at 12:36

2 Answers2

1

Use preg_match_all(), like this:

$input = 'hellooommm';
$n = preg_match_all('/(.)\1{2}/', $input);
if ($n !== false) {
    echo "$n matches found", PHP_EOL;
} else {
    echo "an error occurred when calling preg_match_all()", PHP_EOL;
}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

@hek2mgl's answer above is simple and eloquently solves the problem using regex. But I get the feeling you may benefit from hashing this out logically a bit more. Another approach you could use is iterating over the characters and counting the repetitions like this:

function countGroupsOfThree($str) {
    $length = strlen($str);
    $count = 1;
    $groups = 0;
    for ($i = 0; $i < $length; $i++){
        // is this character the same as the last one?
        if ($i && $str[$i] === $str[$i-1]) {
            // if so, increment the counter
            $count++;
            // is this the third repeated character in a row?
            if ($count == 3) {
                // if so, increment $groups
                $groups++;
            }
        } else {
            // if not, reset the counter
            $count = 1;
        }
    }
    return $groups;
}

$str = 'aaavgfwbbb3ds';
echo countGroupsOfThree($str);

OUTPUT: 2

In the grand scheme of things, this function is probably not very useful but hopefully it illustrates some key concepts that will help you figure things like this out in the future.