在 php 中转换 youtube Api v3 视频持续时间

2022-01-19 00:00:00 regex youtube-api php

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

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

但这段代码只给我 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;
}

相关文章