Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert separators into a string in regular intervals

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 :)

like image 638
Baloo Avatar asked Sep 03 '25 14:09

Baloo


1 Answers

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()
  • www.w3schools.com - str_split()
  • www.w3schools.com - implode()

On the same topic :

  • Split string into equal parts using PHP
like image 84
Colin Hebert Avatar answered Sep 05 '25 05:09

Colin Hebert