Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
September 22, 2017

Web Dev Tid Bit: Grabbing the ID of a YouTube URL in PHP

Web Dev Tid Bit: Grabbing the ID of a YouTube URL in PHP

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 “” ,  the shortened URL “”, and the embed URL “”.

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.)?(?|*&)?v(?:i)?=|(?:embed|v|vi|user)/))([^?&"'>]+)/", $url, $video_parts);
      $params['id'] = $video_parts[1];
      $params['id'] = $url;

   preg_match("/list=(.*)&?/?/", $url, $video_parts);
      $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('') );

Will give you a return of:

    [id] => 1Mlhnt0jMlg

From there you can use that ID to formulate a different/correct URL or use it in a completely different way!

Nick Kalscheur

Nick Kalscheur

Lead Developer