DiegoP. DiegoP. - 2 months ago 6
PHP Question

PHP count, add colons every 2 characters

I have this string


I need to count the last 6 characters starting from the end of this string (because it could may be long starting from the begin)

Then I need to add colons after every 2 characters.

So after counting 6 characters from the end it will be


After having added the colons it will look like:


Can you help me achieving it?

I do not really know where to start!

Thank you


You can do this with substr, str_split and implode

The code is done on multiple lines for clarity, but can easily be done in a chain on one line:

$str = '1010081-COP-8-27-20110616214459';
//Get last 6 chars
$end = substr($str, -6);
//Split string into an array.  Each element is 2 chars
$chunks = str_split($end, 2);
//Convert array to string.  Each element separated by the given separator.
$result = implode(':', $chunks);