在PHP中转换YouTube Api v3视频时长 [英] Convert youtube Api v3 video duration in php

查看:90
本文介绍了在PHP中转换YouTube Api v3视频时长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将PT2H34M25S转换为2:34:25

how do i convert PT2H34M25S to 2:34:25

我搜索并使用了此代码.我是regex的新手,有人可以解释一下吗?并帮助我解决问题

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;
    }   

但是此代码仅给我HH:MM

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;
        }

推荐答案

在创建$parts变量后,您应该查看一下.

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.

这是一个更新的函数,用于处理缺失的数值(如果省略了小时或分钟)和超过60的秒/小时(不确定是否会发生).这不会验证数字的标签:

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个数字:假设是秒数
  • 2个数字:假设是分钟,秒
  • 3个或更多数字:假设前3个数字是小时,分钟,秒(忽略其他数字)

可以添加更多验证来验证输入字符串.

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;
}

这篇关于在PHP中转换YouTube Api v3视频时长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆