We make a lot of templates that work with YouTube videos. Most of these videos are added by the client via a text field asking for the “YouTube URL”. What they put in there is not always exactly what you need for your particular application. For instance, there is the standard watching url you would see if you go to YouTube.com “https://www.youtube.com/watch?v=1Mlhnt0jMlg” , the shortened URL “https://youtu.be/1Mlhnt0jMlg”, and the embed URL “https://www.youtube.com/embed/1Mlhnt0jMlg”.
It isn’t realistic to expect a client to always know to give a specific version of the URL, and making any fields asking for just the YouTube ID is also inviting issues for some non tech-savvy people.
So what can we do?
Luckily there is a nifty little PHP function I’ve been using that I’ve found and tweaked that should get the ID of your the video every time ( as of September 2017 at least ).
function pk_get_youtube_params($url){ $params = array(); //Video ID preg_match("/^(?:http(?:s)?://)?(?:www.)?(?:m.)?(?:youtu.be/|youtube.com/(?:(?:watch)??(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)/))([^?&"'>]+)/", $url, $video_parts); if(isset($video_parts[1])){ $params['id'] = $video_parts[1]; }else{ $params['id'] = $url; } //Playlist preg_match("/list=(.*)&?/?/", $url, $video_parts); if(isset($video_parts[1])){ $params['list'] = $video_parts[1]; } return $params; }
This uses a regular expression to find any iteration of a YouTube URL and to grab the relevant part that is the ID and return it as an array. As an added bonus, it also returns the playlist list ID if there is one present as well. So running this code:
print_r( pk_get_youtube_params('https://youtu.be/1Mlhnt0jMlg') );
Will give you a return of:
Array ( [id] => 1Mlhnt0jMlg )
From there you can use that ID to formulate a different/correct URL or use it in a completely different way!