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

时间:2014-12-01 18:24:11

标签: 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, $s = 20
$time = "PT6M14S"; -> $h = 0, $m = 6, $s = 14
$time = "PT11S"; -> $h = 0, $m = 0, $s = 11

2 个答案:

答案 0 :(得分:0)

(\d+)(?=h\b)|(\d+)(?=m\b)|(\d+)(?=s\b)

试试这个。抓取$1h$2m,依此类推。请参阅演示。

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

答案 1 :(得分:0)

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

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
//)