I got this code:
if(preg_match("/^(?:https?:\/\/)?(?:www\.)?youtu(.be\/|be\.com\/watch\?v=)(\w{11})$/", $url)){
preg_match("/^(?:https?:\/\/)?(?:www\.)?youtu(.be\/|be\.com\/watch\?v=)(\w{11})$/", $url, $matches);
$vid = str_replace(' ', '', $matches[0]);
}
That pretty much checks if the URL is a Youtube video. How do I assign the last 11 characters from the URL to the $vid
variable?
Example:
URL: https://www.youtube.com/watch?v=ASDASDASDAS
$vid = ASDASDASDAS
First, you don't want to check for the last 11 characters, because the video ID might be changed any time to a different length. What you should always do is make something flexible enough. So in this case, you should check for ?.*v=([^&]+)
, since that will get the match until the next &
. So your code would look like this:
//make this a variable, since you're using it multiple times.
$re = "/^(?:https?:\/\/)?(?:www\.)?youtu(.be|be\.com)\/watch\?.*?v=([^&#]+).*$/";
if (preg_match($re, $url)){
preg_match($re, $url, $matches);
$vid = $matches[2]; //the 2nd group in the match, so the 2nd set of ()s
}
In that code, video urls that contain other URL parameters will also still work, and it's much more flexible with the length of the video ID.
Demo - look to the right where it says 2.
, it will mention the video ID there (which is what's put inside $vid
).
Perhaps something like:
$vid = substr($url,strlen($url)-11);
The parse_str and parse_url functions will do the job ( no need for regular expressions ):
$link = 'https://www.youtube.com/watch?v=ASDASDASDAS';
parse_str( parse_url( $link, PHP_URL_QUERY ), $query );
print_r( $query );
/*
Array
(
[v] => ASDASDASDAS
)
*/
The straightforward (correct) answers have been made, but I would encourage you to take a look at oembed standard and library for php like https://code.google.com/p/php-oembed/. This would help you get info from almost all image/video services out there, generate embed code and more.