Created
June 22, 2020 23:01
-
-
Save adamcrampton/995837d674bcf30253e6ad037d7797be to your computer and use it in GitHub Desktop.
Parse YouTube duration string to seconds integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Match pattern PT#H#M#S (leading PT, hours, minutes, seconds) and return seconds value. | |
* | |
* @param string $string | |
* @return int | |
*/ | |
private static function convertDuration($string) | |
{ | |
// Comprehensive regex that should match any value. | |
// Keys: | |
// 0 => Original string | |
// 5 => Hours | |
// 6 => Minutes | |
// 7 => Seconds | |
preg_match('/^(-|)?P([0-9]+Y|)?([0-9]+M|)?([0-9]+D|)?T?([0-9]+H|)?([0-9]+M|)?([0-9]+S|)?$/', $string, $matches); | |
// Strip leading characters. | |
foreach($matches as &$match): | |
$match = intval(preg_replace('/((?!([0-9]|-)).)*/', '', $match)); | |
endforeach; | |
// Return total seconds. | |
return ($match[5] * 3600) + ($match[6] * 60) + $match[7]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment