2014-12-01 70 views
0

我通過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 
+0

@ Rizier123算不了什麼,我不知道如何做到這一點。 – Muki 2014-12-01 18:27:19

回答

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

我試過'%^ PT(?:(\ d +)H)?(?:(\ d +)M)?(\ d +)S $%'。如果一段視頻長3米,那麼字符串將是「PT3M」,這是行不通的,有沒有辦法解決這個問題? 編輯:我改變它爲'^ PT(?:(\ d +)H)?(?:(\ d +)M)?(?:(\ d +)S)?$'這似乎是工作,是這正確的方法? – Muki 2014-12-01 20:12:15

+0

現在您可以放心使用。 ;) – 2014-12-02 13:07:50

+0

@Muki你檢查這個嗎? – 2014-12-02 18:11:55

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

嘗試this.Grab $1h$2m等on.See演示。

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

我試過這個,但它不起作用,匹配[1-3]沒有匹配,re不適用於字符串,比如「PT6M14S」,請看這裏:http://regex101.com/r/ aZ5fJ5/1 – Muki 2014-12-01 19:02:38