user3701398 user3701398 - 3 months ago 9
PHP Question

exploding a timestamp and adding : every 2 places

I have a PHP Script that has an INT in the format MMSSMS - Minutes Seconds Milliseconds defined as $time. I just need a : every 2 places in $time. Any help is appreciated.

Example: $message = 'I clocked in (MM:SS:MS) '.$time.';

the issue is the $time displays as 000044 instead 00:00:44 on echo

Answer

This code replaces 2 consecutive digits not on the end of the string with the digits followed by colon

$message = 'I clocked in (MM:SS:MS) '.preg_replace('/\d{2}(?!$)/','$0:',$time);

php.net/preg_replace

demo: http://sandbox.onlinephpfunctions.com/code/de0ce1e4466ff747f1bba2ac92331623a1b234ed

Comments