Skip to content
Advertisement

php split / cluster binary into chunks based on next 1 in cycle

I need to figure out a method using PHP to chunk the 1’s and 0’s into sections.

1001 would look like: array(100,1)


1001110110010011 would look like: array(100,1,1,10,1,100,100,1,1)

It gets different when the sequence starts with 0’s… I would like it to segment the first 0’s into their own blocks until the first 1 is reached)

00110110 would look like (0,0,1,10,1,10)

How would this be done with PHP?

Advertisement

Answer

You can use preg_match_all to split your string, using the following regex:

10*|0

This matches either a 1 followed by some number of 0s, or a 0. Since a regex always tries to match the parts of an alternation in the order they occur, the second part will only match 0s that are not preceded by a 1, that is those at the start of the string. PHP usage:

$beatstr = '1001110110010011';
preg_match_all('/10*|0/', $beatstr, $m);
print_r($m);
$beatstr = '00110110';
preg_match_all('/10*|0/', $beatstr, $m);
print_r($m);

Output:

Array
(
    [0] => Array
        (
            [0] => 100
            [1] => 1
            [2] => 1
            [3] => 10
            [4] => 1
            [5] => 100
            [6] => 100
            [7] => 1
            [8] => 1
        )
)
Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 1
            [3] => 10
            [4] => 1
            [5] => 10
        )
)

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement