Php – Using PHP and regex, insert a character between a group of matched characters

PHPregex

I would like to insert a character between a group of matched characters using regex to define the group and PHP to place the character within the match. Looking here, I see that it may require PHP recursive matching, although I imagine there could be a simpler way.

To illustrate, I am attempting to insert a space in a string when there is a combination of 2 or more letters adjacent to a number. The space should be inserted between the letters and number(s). The example, "AXR900DE3", should return "AXR 900 DE 3".

Could an answer be to use preg_split to break up the string iteratively and insert spaces along the way?
I've begun an attempt using preg_replace below for the pattern 2+letters followed by a number (I will also need to use a pattern, a number followed by 2+letters), but I need another step to insert the space between that match.

$sku = "AXR900DEF334";
$string = preg_replace('/(?<=[A-Z]{2}[\d])/',' ', $sku);

Best Answer

You don't need to do recursive. If I have understood you correctly, you should be able to do this:

$sku = "AXR900DEF334";
$string = preg_replace('/((?<=[A-Z]{2})(?=[0-9])|(?<=[0-9])(?=[A-Z]{2}))/',' ', $sku);
echo $string;

OUTPUT

AXR 900 DEF 334

This will match both when the letters precedes and comes after the digits.