Say I have a list of IDs like so:
http://www.youtube.com/watch?v=KMU0tzLwhbE
http://youtu.be/KMU0tzLwhbE
http://www.youtube.com/watch?v=KMU0tzLwhbE&featured=
Try something like:
$pattern = '/(?:(?:\?|&)v=|\/)([A-Za-z0-9]{11})/';
$url = 'http://www.youtube.com/watch?v=KMU0tzLwhbE';
preg_match($pattern, $url, $matches);
echo $matches[1];
The first group of a preg_match
using (?:(?:\?|&)v=|youtu\.be\/)(.+?)(?:$|&)
as the pattern.
Try this:
$video_url = "http://www.youtube.com/watch?v=KMU0tzLwhbE"; // http://youtu.be/KMU0tzLwhbE
$url_parts = parse_url($video_url);
if (isset($url_parts["query"]) && (strpos($url_parts["query"], "v") !== false)) {
parse_str($url_parts["query"], $vars);
// Handle full URLs with query string like 'http://www.youtube.com/watch?v=KMU0tzLwhbE'
if (isset($vars["v"]) && $vars["v"]) {
$video_code = $vars["v"];
// Handle the new short URLs like 'http://youtu.be/KMU0tzLwhbE'
} else if ($url_parts['path']) {
$video_code = trim($url_parts['path'], '/');
}
}
Simply im using this, because url is same for all youtube videos
$ytid = str_replace('http://www.youtube.com/watch?v=', '','http://www.youtube.com/watch?v=bZP4nUFVC6s' );
you can check for the other url variations as well
Do not use regexes for this. URIs have a particular grammar and PHP gives you the tools required to parse each URL properly. See parse_url() and parse_str().
<?php
function getYoutubeVideoId($url) {
$urlParts = parse_url($url);
if($urlParts === false || !isset($urlParts['host']))
return false;
if(strtolower($urlParts['host']) === 'youtu.be')
return ltrim($urlParts['path'], '/');
if(preg_match('/^(?:www\.)?youtube\.com$/i', $urlParts['host']) && isset($urlParts['query'])) {
parse_str($urlParts['query'], $queryParts);
if(isset($queryParts['v']))
return $queryParts['v'];
}
return false;
}