2

I am trying to break a string of binary ones and zeros into groups of four. After reading the manual and the posts I am missing something:

$subject = "101010101";

$pattern = "/.{1,4}/";

$blocks = preg_split ($pattern, $subject);

print_r($blocks);

The result is an empty array.

Array
(
    [0] =>
    [1] =>
    [2] =>
    [3] =>
)
php >
1
  • preg_split() uses the regex to identify the delimiter. You don't need regex for this job, str_split() is better because it is faster (and easier to understand). Commented Jul 28, 2019 at 11:47

5 Answers 5

3

You could just use str_split() which will split your string into an array of strings of size n.

$subject = "101010101";
$split = str_split($subject, 4);
print_r($split);

Output:

Array
(
    [0] => 1010
    [1] => 1010
    [2] => 1
)
Sign up to request clarification or add additional context in comments.

Comments

2

You get that result because you are matching 1 - 4 characters to split on. It will match all the characters in the string leaving nothing to display.

If you want to use a regex to break it up into groups of 4 (and the last one because there are 9 characters) you could use preg_match_all and match only 0 or 1 using a character class instead of using a dot which will match any character except a newline.

[01]{1,4}

Regex demo | Php demo

$subject = "101010101";
$pattern = "/[01]{1,4}/";
$blocks = preg_match_all ($pattern, $subject, $matches);

print_r($matches[0]);

Result

Array
(
    [0] => 1010
    [1] => 1010
    [2] => 1
)

Comments

2

Any char in a string match your pattern, in other words, any string contains only delimiters. And result contains zero-sized spaces.

The get expected result you need capture only delimiters. You can do that adding two flags

$blocks = preg_split ($pattern, $subject, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );

demo

Comments

2

You can set PREG_SPLIT_DELIM_CAPTURE flag to get captured pattern in output

If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. PHP reference

Note:- You need to add the pattern into capturing group () to get it in ouput


$subject = "101010101";

$pattern = "/(.{1,4})/";

$blocks = preg_split ($pattern, $subject, null,  PREG_SPLIT_DELIM_CAPTURE);

print_r($blocks);

Comments

2

preg_split() returns an array containing substrings of subject split along boundaries matched by pattern, or FALSE on failure.. But you are trying to grab 1-4 characters group from that string. So preg_match_all() can be used for this purpose. Example:

$subject = "101010101";
$pattern = "/[01]{1,4}/";
preg_match_all($pattern, $subject, $match);

echo '<pre>', print_r($match[0]);

Comments

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.