Daniel Euchar Daniel Euchar - 15 days ago 8
PHP Question

Convert youtube Api v3 video duration in php

how do i convert PT2H34M25S to 2:34:25

I searched and used this code. I'm new to regex can someone explain this ? and help me with my issue

function covtime($youtube_time){
preg_match_all('/(\d+)/',$youtube_time,$parts);
$hours = floor($parts[0][0]/60);
$minutes = $parts[0][0]%60;
$seconds = $parts[0][1];
if($hours != 0)
return $hours.':'.$minutes.':'.$seconds;
else
return $minutes.':'.$seconds;
}


but this code only give me HH:MM

so dumb found the solution :

function covtime($youtube_time){
preg_match_all('/(\d+)/',$youtube_time,$parts);
$hours = $parts[0][0];
$minutes = $parts[0][1];
$seconds = $parts[0][2];
if($seconds != 0)
return $hours.':'.$minutes.':'.$seconds;
else
return $hours.':'.$minutes;
}

Answer

You should take a look at your $parts variable after it's created.

var_dump($parts);

Compare that output with how you are defining your variables. It should stand out pretty obviously after that.

I guess my next question after that is what variations of the input time string are you expecting and what validation will you be doing? The variations of the input format you want to handle will affect the complexity of the actual code written.

Edit: Here is an updated function to handle missing numeric values (if the hours or minutes is omitted) and seconds/hours over 60 (not sure if this will ever happen). This doesn't validate the label for the numbers:

  • 1 number: assume it is seconds
  • 2 numbers: assume it is minutes, seconds
  • 3 or more numbers: assume first 3 numbers are hours, minutes, seconds (ignoring another numbers)

More validation can be added to look into validating the input string.

<?php
function covtime($youtube_time) {
    preg_match_all('/(\d+)/',$youtube_time,$parts);

    // Put in zeros if we have less than 3 numbers.
    if (count($parts[0]) == 1) {
        array_unshift($parts[0], "0", "0");
    } elseif (count($parts[0]) == 2) {
        array_unshift($parts[0], "0");
    }

    $sec_init = $parts[0][2];
    $seconds = $sec_init%60;
    $seconds_overflow = floor($sec_init/60);

    $min_init = $parts[0][1] + $seconds_overflow;
    $minutes = ($min_init)%60;
    $minutes_overflow = floor(($min_init)/60);

    $hours = $parts[0][0] + $minutes_overflow;

    if($hours != 0)
        return $hours.':'.$minutes.':'.$seconds;
    else
        return $minutes.':'.$seconds;
}