1

I'm on search for a php snipped to cut following binary code:

$code = "10011";

I need from $code an explode array like $codes = array(100,1,1); for example:

echo $codes[0]; // echo result: 100

I'm not sure what php function is helpful, thank you very much for help!

2
  • In other words, you want to split the string before each 1? Commented Jan 26, 2018 at 22:31
  • yes, that's right: 1000100101 = 1000, 100, 10, 1 Commented Jan 26, 2018 at 22:31

1 Answer 1

2

With a regex, a 1 with zero or more 0:

preg_match_all('~10*~', $str, $m);
print_r($m[0]);

If your string eventually starts with one or more zeros, you can change it to:

preg_match_all('~10*|0+~', $str, $m);
Sign up to request clarification or add additional context in comments.

10 Comments

wow! that's smart solution. thank you very much, you made my day :)
and if I need 1000101 = 1000000, 100, 1 one more example: 101001100 = 100000000, 1000000, 1000, 100
@Korty: something like this or this but I'm sure there's a better way to do that.
@Korty: refresh the page, I edited the comment. Better, this one
@Korty: I'm sure you will find how to do it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.