Real Dreams
Real Dreams

Reputation: 18010

Spliting a string to fixed-size chunks using only RegEx

preg_split('#(?=.)(?<=.)#u','asfaaasfdf'); produces:

Array
(
    [0] => a
    [1] => s
    [2] => f
    [3] => a
    [4] => a
    [5] => a
    [6] => s
    [7] => f
    [8] => d
    [9] => f
)

How can I only change RegEx and get:

Array
(
    [0] => as
    [1] => fa
    [2] => aa
    [3] => sf
    [4] => df
)

or:

Array
(
    [0] => asf
    [1] => aaa
    [2] => sfd
    [3] => f
)

Upvotes: 3

Views: 89

Answers (1)

Qtax
Qtax

Reputation: 33908

Why use split? Use match:

preg_match_all('/.{1,3}/s', 'asfaaasfdf', $matches);
print_r($matches[0]);

Output:

Array
(
    [0] => asf
    [1] => aaa
    [2] => sfd
    [3] => f
)

Upvotes: 2

Related Questions