简体   繁体   中英

How can I split a string into an array of substrings with regular expressions in PHP?

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 >

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
)

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
)

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]);

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM