i need a PHP code to find longest contiguous sequence of characters in the string

Using
preg_match_all to get sequences of repeating characters,
array_map along with strlen to get the string length of each sequence
max to get the biggest value in the array.

Consider the following example:

$string =  "aaabababbbbbaaaaabbbbbbbbaa";

preg_match_all('#(\w)\1+#',$string,$matches);

print_r($matches);

Will output

Array
(
    [0] => Array
        (
            [0] => aaa
            [1] => bbbbb
            [2] => aaaaa
            [3] => bbbbbbbb
            [4] => aa
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => a
            [3] => b
            [4] => a
        )

)

Next we get the sizes for each string of repeating characters

$sizes = array_map('strlen', $matches[0]);
print_r($sizes);

Will output

Array
(
    [0] => 3
    [1] => 5
    [2] => 5
    [3] => 8
    [4] => 2
)

Now let’s get the biggest value of the $sizes array

print max($sizes);

Will give us

8

We need the key for the max value to pick up the letter

$maxKey = array_keys($sizes, max($sizes));

print $matches[1][$maxKey[0]];

Will output

b

Leave a Comment