Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 views
in Technique[技术] by (71.8m points)

regex - 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;
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using DateTime class

You could use PHP's DateTime class to achieve this. This solution is much simpler, and will work even if the format of the quantities in the string are in different order. A regex solution will (most likely) break in such cases.

In PHP, PT2H34M25S is a valid date period string, and is understood by the DateTime parser. We then make use of this fact, and just add it to the Unix epoch using add() method. Then you can format the resulting date to obtain the required results:

function covtime($youtube_time){
    if($youtube_time) {
        $start = new DateTime('@0'); // Unix epoch
        $start->add(new DateInterval($youtube_time));
        $youtube_time = $start->format('H:i:s');
    }
    
    return $youtube_time;
}   

echo covtime('PT2H34M25S');

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...