PHP count, adding colons every 2 characters

I have this line

1010081-COP-8-27-20110616214459 

I need to count the last 6 characters starting from the end of this line (because it can last from the very beginning)

Then I need to add colons after every two characters.

So, after counting 6 characters from the end will be

 214459 

After adding a colon, it will look like this:

 21:44:59 

Can you help me achieve this?

I don’t know where to start!

thanks

+7
source share
4 answers

You can do this with substr , str_split and implode

The code is done on several lines for clarity, but can be easily executed 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); 
+10
source
 echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string); 

It seems to me that this line has a certain format, which should be analyzed for data. Something like:

 sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp); $timestamp = strtotime($timestamp); echo date('Ymd H:i:s', $timestamp); 
+12
source

If you just need time:

 $time = rtrim(chunk_split(substr($s,-6),2,':'),':'); 
+1
source
 $final = "1010081-COP-8-27-20110616214459"; $c = substr($final, -2); $b = substr($final, -4, 2); $a = substr($final, -6, 2); echo "$a:$b:$c"; 
+1
source

All Articles