Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spliting a string to fixed-size chunks using only RegEx

Tags:

regex

php

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
)
like image 221
Handsome Nerd Avatar asked Sep 12 '26 07:09

Handsome Nerd


1 Answers

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
)
like image 86
Qtax Avatar answered Sep 14 '26 20:09

Qtax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!