Question: I have the following string in php:

```
$string = 'FEDCBA9876543210';

```

The string can be have 2 or more (I mean **more**) hexadecimal characters
I wanted to group string by 2 like :

```
$output_string = 'FE:DC:BA:98:76:54:32:10';

```

I wanted to use regex for that, I think I saw a way to do like "recursive regex" but I can't remember it.

Any help appreciated :)

Answer: 
If you don't need to check the content, there is no use for regex.

Try this

```
$outputString = chunk_split($string, 2, ":");
// generates: FE:DC:BA:98:76:54:32:10:

```

You might need to remove the last ":".

Or this :

```
$outputString = implode(":", str_split($string, 2));
// generates: FE:DC:BA:98:76:54:32:10

```

---

**Resources :**

* [www.w3schools.com - chunk\_split()](http://www.w3schools.com/php/func_string_chunk_split.asp)
* [www.w3schools.com - str\_split()](http://www.w3schools.com/php/func_string_str_split.asp)
* [www.w3schools.com - implode()](http://www.w3schools.com/php/func_string_implode.asp)

**On the same topic :**

* [Split string into equal parts using PHP](https://stackoverflow.com/questions/1794006/split-string-into-equal-parts-using-php)
While it is not horrible practice to use `rtrim(chunk_split($string, 2, ':'), ':')`, I prefer to use direct techniques that avoid "mopping up" after making modifications.

Code: ([Demo](https://3v4l.org/RHIaJ))

```
$string = 'FEDCBA9876543210';
echo preg_replace('~[\dA-F]{2}(?!$)\K~', ':', $string);

```

Output:

```
FE:DC:BA:98:76:54:32:10

```

Don't be intimidated by the regex. The pattern says:

```
[\dA-F]{2}   # match exactly two numeric or A through F characters
(?!$)        # that is not located at the end of the string
\K           # restart the fullstring match

```

When I say "restart the fullstring match" I mean "forget the previously matched characters and start matching from this point forward". Because there are no additional characters matched after `\K`, the pattern effectively delivers the zero-width position where the colon should be inserted. In this way, no original characters are lost in the replacement.