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.

JavaScript

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)

JavaScript

How would this be done with PHP?

Advertisement

Answer

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

JavaScript

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:

JavaScript

Output:

JavaScript

Demo on 3v4l.org

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