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


Separate string value to different variables

我正在通过 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

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

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
//)
('d+)(?=h'b)|('d+)(?=m'b)|('d+)(?=s'b)

试试这个。抓取$1 h$2 m等。请参阅演示。

http://regex101.com/r/vF0kU2/10

$re = "/(''d+)(?=h''b)|(''d+)(?=m''b)|(''d+)(?=s''b)/m";
$str = "'$time = '"PT1H50M20S'"; (Video is 1h 50m 20s long)'n'$time = '"PT6M14S'"; (Video is 6m 14s long)'n'$time = '"PT11S'"; (Video is 11s long)'n";
preg_match_all($re, $str, $matches);