Count the successive occurrence of specific identical characters in a string - PHP

I try to calculate several “bands”, in particular the greatest number of wins and losses in a row, but also most cases of games without a win, without a loss.

I have a line that looks like this: 'WWWDDWWWLLWLLLL'

To do this, I need to return:

  • The longest sequential start of the W charector (then I replicate for L)
  • The longest sequential start without a W charector (then I replicate for L)

I found and adapted the next one that will go through my array and tell me the longest sequence, but I cannot adapt it to fit the above criteria.

All help and training was highly appreciated :)

    function getLongestSequence($sequence){
$sl = strlen($sequence);
$longest = 0;
for($i = 0; $i < $sl; )
{
$substr = substr($sequence, $i);
$len = strspn($substr, $substr{0});if($len > $longest)
$longest = $len;
$i += $len;
}
return $longest;
}
echo getLongestSequence($sequence);
0
2

:

$string = 'WWWDDWWWLLWLLLL';
// The regex matches any character -> . in a capture group ()
// plus as much identical characters as possible following it -> \1+
$pattern = '/(.)\1+/';

preg_match_all($pattern, $string, $m);
// sort by their length
usort($m[0], function($a, $b) {
    return (strlen($a) < strlen($b)) ? 1 : -1;
});

echo "Longest sequence: " . $m[0][0] . PHP_EOL;
+2

, .

       $string = "WWWDDWWWLLWLLLL";
        function getLongestSequence($str,$c) {
        $len = strlen($str);
        $maximum=0;
        $count=0;
        for($i=0;$i<$len;$i++){
            if(substr($str,$i,1)==$c){
                $count++;
                if($count>$maximum) $maximum=$count;
            }else $count=0;
        }
        return $maximum;
        }
        $match="W";//change to L for lost count D for draw count
        echo getLongestSequence($string,$match);
0

Source: https://habr.com/ru/post/1650830/


All Articles