Php 将字符串值分隔为不同的变量

Php 将字符串值分隔为不同的变量,php,regex,Php,Regex,我通过Youtube API提取一个字符串,该字符串给出视频的长度,该字符串可以有不同的值,例如: $time = "PT1H50M20S"; (Video is 1h 50m 20s long) $time = "PT6M14S"; (Video is 6m 14s long) $time = "PT11S"; (Video is 11s long) 如何在单独的变量中保存小时、分钟和秒?上述代码应给出: $time = "PT1H50M20S"; -> $h = 5, $m = 50

我通过Youtube API提取一个字符串,该字符串给出视频的长度,该字符串可以有不同的值,例如:

$time = "PT1H50M20S"; (Video is 1h 50m 20s long)
$time = "PT6M14S"; (Video is 6m 14s long)
$time = "PT11S"; (Video is 11s long)
如何在单独的变量中保存小时、分钟和秒?上述代码应给出:

$time = "PT1H50M20S"; -> $h = 5, $m = 50, $s = 20
$time = "PT6M14S"; -> $h = 0, $m = 6, $s = 14
$time = "PT11S"; -> $h = 0, $m = 0, $s = 11
试试这个。抓取
$1
作为
h
$2
作为
m
等等。参见演示


可以使用此函数将字符串转换为有效时间

function getDuration($str){
    $result = array('h' => 0, 'm' => 0, 's' => 0);
    if(!preg_match('%^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$%',$str, $matches)) return $result;

    if(isset($matches[1]) && !empty($matches[1])) $result['h'] = $matches[1];
    if(isset($matches[2]) && !empty($matches[2])) $result['m'] = $matches[2];
    if(isset($matches[3]) && !empty($matches[3])) $result['s'] = $matches[3];

    return $result;
}
结果:

print_r(getDuration('PT1H50M20S'));

//Array
//(
//    [h] => 1
//    [m] => 50
//    [s] => 20
//)

@Rizier123还没有,我不知道怎么做。我尝试了这个,但它不起作用,在匹配[1-3]上没有匹配项,re对字符串如“PT6M14S”不起作用,请参见这里:我尝试了
%^PT(?(\d+)H)?(?:(\d+)M)?(\d+)S$%
,对一些视频有效。如果一个视频是3米长,那么字符串将是“PT3M”,这不起作用,有没有办法解决这个问题?编辑:我把它改成了
^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$
这似乎有效,这是正确的方法吗?现在你可以放心使用了。;)@木奇,你查过了吗?是的,很抱歉回复晚了,谢谢你的帮助!
function getDuration($str){
    $result = array('h' => 0, 'm' => 0, 's' => 0);
    if(!preg_match('%^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$%',$str, $matches)) return $result;

    if(isset($matches[1]) && !empty($matches[1])) $result['h'] = $matches[1];
    if(isset($matches[2]) && !empty($matches[2])) $result['m'] = $matches[2];
    if(isset($matches[3]) && !empty($matches[3])) $result['s'] = $matches[3];

    return $result;
}
print_r(getDuration('PT1H50M20S'));

//Array
//(
//    [h] => 1
//    [m] => 50
//    [s] => 20
//)