Search code examples
phpregexdatetimeexplode

What is the best way to split this string value up?


The string value will be something like P0DT0H4M13S

P can be ignored.
0D is the DAY
0H is the HOUR
4M is the MINUTE
13S is the SECOND

It would be nice to do something like 4:13.

If there is a day then 1 DAY 4:13

HOUR AND DAY can be 1 DAY 4:4:13

I was trying to explode it, but that just seems silly, is there a regex that can handle this split?

THANKS!


Solution

  • That's a PHP DateInterval string, and should be processed using that class. For example:

    $str = 'P0DT0H4M13S';
    
    $interval = new DateInterval($str);
    $output = '';
    if ($interval->d) {
        $output = $interval->format('%d DAY ');
    }
    $output .= $interval->format('%H:%I:%S');
    echo $output;
    

    Output:

    00:04:13
    

    Demo on 3v4l.org

    Obviously the code can be modified to skip the hour in the same way as the day if desired.