Lucas Young
Lucas Young

Reputation: 187

Find the length of the longest consecutive sequence of a selected character in a string (PHP)?

How would I find the length of the longest consecutive sequence of a selected character in a string?

What I'm trying to do is see if 0 occurs five or more times in a string like this

"111010110101010000010010100000000000111"

The function I need would take a string and a character and in the example above, return 11 for the character 0

Many thanks in advance, gurus :)

Upvotes: 2

Views: 1347

Answers (3)

loveNoHate
loveNoHate

Reputation: 1547

Here you go with a regex:

function highCount($string, $select) {
  preg_match_all("/($select+)\1*/", $string, $find);
  foreach($find[0] as $single) {  
    $length[] = strlen($single);
  }
  return max($length);
}

//11
echo highCount("111010110101010000010010100000000000111", 0);

Demo.

Upvotes: 1

Ormoz
Ormoz

Reputation: 3013

You may try this:

 function myFunc($input_string,$find)
 {
 $string=preg_replace("^$find","-",$input_tring);
 $array=explode("-",$string);
 $array=array_diff($array, array(""));
 asort($array);
 return strlen($array[0]);
 }

I assumed that the - character does not appear in your find criteria.

Upvotes: 0

Nathan Parker
Nathan Parker

Reputation: 308

I guess there should be a more efficient way to achieve this, maybe with regexp, but, still, here is what I came with

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;
}

Hope that helps!

Edit: If you want it to only check if the char appears more than X times consecutively, there is a more efficient way to achieve that. This function will return true if the selected char appears more than X times, and false if not.

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;
}

Upvotes: 1

Related Questions