'How can I split string into groups using regex

I'm trying to split the string 'A123456789123B' into six groups using the following regular expression:

'/^([A-Z]{1})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([A-Z]{1})$/'

I tried using:

preg_split('/^([A-Z]{1})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([A-Z]{1})$/', 'A123456789123B');

However, it does not work.

I need to split the string into something like this:

['A', '123', '456', '789', '123', 'B']


Solution 1:[1]

I think you should rather use preg_match cause split will search for a separator and you have none here :

$str = 'A123456789123B';
preg_match('/^([A-Z]{1})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([A-Z]{1})$/', $str, $matches);
var_dump($matches);

Then you'll have to remove the first key of $matches :

if ($matches) {
    array_shift($matches)
}

Solution 2:[2]

preg_split() is perfectly suited to directly providing the desired result.

Match the first character in the string or three consecutive characters, the release the matched characters with \K so that no characters are lost in the explosion.

Code: (Demo)

$str = "A123456789123B";

var_export(
    preg_split('/(?:^.|...)\K/', $str)
);

Output:

array (
  0 => 'A',
  1 => '123',
  2 => '456',
  3 => '789',
  4 => '123',
  5 => 'B',
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jiboulex
Solution 2 mickmackusa