String
PHP Advanced String Helper
Categories:
Get the video id and the video start time from the youtube
function getYouTubeVideoIdAndStartTime($url) {
$videoId = '';
$startTime = '';
// Check if the URL has the "youtu.be" domain
if (strpos($url, 'youtu.be') !== false) {
$urlParts = explode('/', $url);
$videoIdWithParams = end($urlParts);
$videoIdParts = explode('?', $videoIdWithParams);
$videoId = $videoIdParts[0];
} else {
$pattern = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|v\/|\.be\/|watch\?.*?&v=))([\w-]+)/i';
preg_match($pattern, $url, $matches);
if (isset($matches[1])) {
$videoId = $matches[1];
}
}
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
if (isset($params['t'])) {
$startTime = $params['t'];
} elseif (isset($params['start'])) {
$startTime = $params['start'];
}
return array(
'videoId' => $videoId,
'startTime' => $startTime
);
}