计算字符串中特定相同字符的连续出现次数 - PHP [英] Count consecutive occurence of specific, identical characters in a string - PHP

查看:65
本文介绍了计算字符串中特定相同字符的连续出现次数 - PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算一些连胜",特别是连续获胜和失败的最高次数,以及大多数没有获胜的比赛,没有失败的比赛.

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.

我有一个看起来像这样的字符串;'WWWDDWWWLLWLLLL'

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

为此,我需要能够返回:

For this I need to be able to return:

  • 最长连续运行 W 字符(然后我将复制 L)
  • 最长连续运行没有 W 字符(然后我将复制 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);

推荐答案

您可以使用正则表达式来检测相同字符的序列:

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;

这篇关于计算字符串中特定相同字符的连续出现次数 - PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆