Search code examples
phpstrpos

Get the repeated values of the first character in a string


I have a strings similar to this one,

$string = "01110111011101110111101110111110111111";

I need to get the first character in the string (in this case, 0). I then need to get the positions of all the occurrences of that character in the string. All the occurrences should be put into an array with the first element being 1 (the first occurrence is the first character of the string).

For example, the above string should produce an array like this,

$return_value = array([0]=>1, [1]=>5, [2]=>9, [3]=>13, [4]=> 17....);

Solution

  • This should do the trick,

    $string = "01110111011101110111101110111110111111";
    $offset = 0;
    $return_value = array();
    $character = substr($string, 0, 1);
    
    while (($offset = strpos($string, $character, $offset))!== false) {
        $return_value[] = $offset + 1;
        $offset = $offset + strlen($character);
    }
    
    var_dump($return_value);
    

    Which return_value will produce,

    array(8) { [0]=> int(1) [1]=> int(5) [2]=> int(9) [3]=> int(13) [4]=> int(17) [5]=> int(22) [6]=> int(26) [7]=> int(32)}