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)
You can make sure there are two or more hex characters doing this:

```
if (preg_match('!^\d*[A-F]\d*[A-F][\dA-F]*$!i', $string)) {
  ...
}

```

No need for a recursive regex. By the way, recursive regex is a contradiction in terms. As a regular language (which a regex parses) can't be recursive, by definition.

If you want to also group the characters in pairs with colons in between, ignoring the two hex characters for a second, use:

```
if (preg_match('!^[\dA-F]{2}(?::[A-F][\dA-F]{2})*$!i', $string)) {
  ...
}

```

Now if you want to add the condition requiring tow hex characters, use a [positive lookahead](http://www.regular-expressions.info/lookaround.html):

```
if (preg_match('!^(?=[\d:]*[A-F][\d:]*[A-F])[\dA-F]{2}(?::[A-F][\dA-F]{2})*$!i', $string)) {
  ...
}

```

To explain how this works, the first thing it does it that it checks (with a positive lookahead ie `(?=...)` that you have zero or more digits or colons followed by a hex letter followed by zero or more digits or colons and then a letter. This will ensure there will be two hex letters in the expression.

After the positive lookahead is the original expression that makes sure the string is pairs of hex digits.