tags:

views:

46

answers:

3

Hi,

I have a string like this "0011100001100111", and i would like to know the length of each sequence (00, 111, 0000, 11, 00, 111), in the right order.

How can I do that in PHP ?

Thanks to who will help me.

+5  A: 

create a loop that loops through the entire string. It would look at each character in the string and compare it to the previous character. If it is the same, then it increases a counter, if it is different, it pushes the counter value onto an array and clears the counter.

Untested code:

function countSequenceLengths($str){
  $counter = 1;
  $lastChar = $str[0];
  $ret = array();
  for($i=1; $i<=strlen($str); $i++){
    if($i<strlen($str) && $str[$i] == $lastChar){
      $counter++;
    }else{
      $ret[] = $counter;
      $counter = 1;
      $lastChar = $str[$i];
    }
  }
  return $ret;
}
Marius
edit the first for with $i<=strlen($str)
Marcx
Thanks, fixed :)
Marius
+2  A: 

You could use a regular expression to do that:

preg_split('/(?<=(.))(?!\\1)/', $str)

Here you’re getting an additional empty string at the end that you just need to remove:

array_slice(preg_split('/(?<=(.))(?!\\1)/', $str), 0, -1)
Gumbo
Exactly what i wondered, and of a very short approach, thank you very much.
Michel L'HUILLIER
+1  A: 

The code I made, with your help :

$string = "1111100111111001111110011111100111111001111... ...10011111100111111001";

$str = substr($string, 10, 12);

echo "str = '".$str."'&lt;br /&gt;";

$array = array_slice(preg_split('/(?<=(.))(?!\\1)/', $str), 0, -1);

for($i=0; $i&lt;count($array); $i++){

   echo "array[".$i."] = '".$array[$i]."', ";

   echo "array[".$i."] length = '".strlen($array[$i])."'&lt;br /&gt;";

}

returns me the values I needed :

str = '111001111110'

array[0] = '111', array[0] length = '3'

array[1] = '00', array[1] length = '2'

array[2] = '111111', array[2] length = '6'

array[3] = '0', array[3] length = '1'

Thanks a lot !

Michel L'HUILLIER