php - 查找字符串中选定字符的最长连续序列的长度(PHP)?

标签 php string count

如何找到字符串中选定字符的最长连续序列的长度?

我想做的是看看 0 是否在这样的字符串中出现五次或更多次

“111010110101010000010010100000000000111”

我需要的函数将接受一个字符串和一个字符,在上面的示例中,对于字符 0 返回 11

提前非常感谢各位大师:)

最佳答案

我想应该有一种更有效的方法来实现这一点,也许使用正则表达式,但是,这仍然是我带来的

function howmanytimes($str,$char){
    $maxcount=0;
    $thiscount=0;
    for($i=0;$i<strlen($str);$i++){
        if(substr($str,$i,1)==$char){
            $thiscount++;
            if($thiscount>$maxcount) $maxcount=$thiscount;
        }else $thiscount=0;
    }
    return $maxcount;
}

希望有帮助!

编辑:如果您希望它只检查字符是否连续出现超过 X 次,有一种更有效的方法可以实现这一点。如果所选字符出现超过 X 次,此函数将返回 true,否则返回 false。

function Xtimes($str,$char,$howmanytimes){
$maxcount=0;
$thiscount=0;
for($i=0;$i<strlen($str);$i++){


if(substr($str,$i,1)==$char){
            $thiscount++;
            if($thiscount>$maxcount){
                if($thiscount==$howmanytimes+1){return true;}
                $maxcount=$thiscount;
            }
        }else $thiscount=0;
    }
    return false;
}

关于php - 查找字符串中选定字符的最长连续序列的长度(PHP)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26133134/

相关文章:

php - 从控制台脚本获取 web php.ini 文件的值

php - 在 ubuntu 上安装 curl 以将 hirak/prestissimo 与 Composer 一起使用

php - Doctrine 1 查询中的串联,未知关系别名

c# - C# 中Python 的partition() ?

java - 使用多个分隔符分割查询字符串 - java

python - 在Python中分配数据框中值的渐进计数

mysql - 获取没有计数的记录

php - 使用 PHP 连接到 MySQL 数据库

在查询中跨越多行的 SQL 字符串值

vb.net - 一个字符串在另一个字符串(文本框)中出现多少次 VB.NET