Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP count, add colons every 2 characters

Tags:

php

count

add

I have this string

1010081-COP-8-27-20110616214459

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

214459

After having added the colons it will look like:

21:44:59

Can you help me achieving it?

I do not really know where to start!

Thank you

like image 964
DiegoP. Avatar asked Jun 17 '11 01:06

DiegoP.


2 Answers

echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string);

It looks to me though like that string has a particular format which you should parse into data. Something like:

sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp);
$timestamp = strtotime($timestamp);
echo date('Y-m-d H:i:s', $timestamp);
like image 50
deceze Avatar answered Nov 15 '22 18:11

deceze


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);
like image 21
Explosion Pills Avatar answered Nov 15 '22 19:11

Explosion Pills