Count consecutive occurence of specific, identical characters in a string - PHP

元气小坏坏 提交于 2020-01-07 03:09:08

问题


I am trying to calculate a few 'streaks', specifically the highest number of wins and losses in a row, but also most occurences of games without a win, games without a loss.

I have a string that looks like this; 'WWWDDWWWLLWLLLL'

For this I need to be able to return:

  • Longest consecutive run of W charector (i will then replicate for L)
  • Longest consecutive run without W charector (i will then replicate for L)

I have found and adapted the following which will go through my array and tell me the longest sequence, but I can't seem to adapt it to meet the criteria above.

All help and learning greatly 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);

回答1:


You can use a regular expression to detect sequences of identical characters:

$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:


You can achieve the maximum count of consecutive character in a particular string using the below code.

       $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);


来源:https://stackoverflow.com/questions/26776170/count-consecutive-occurence-of-specific-identical-characters-in-a-string-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!