Extract YouTube ID from Submitted URL

I have a site where i need to allow people to upload a YouTube URL. I want to just store the ID in the MySQL DB and I need to be able to retrieve it later for embedding on the site. Sometimes people will paste a url cleanly like this... "http://www.youtube.com/watch?v=P22G8YHveEg" ..where you could just explode the values at the equals sign and get the second item in the array to parse out the YouTube ID. It is nice to just have the YouTube ID so that you can use it as you need it to retrieve any info about the video that you might need. Sometimes they paste the url like this: "http://www.youtube.com/watch?v=P22G8YHveEg&feature=feedrec_grec_index." So i needed a way to extract the "v" variable out of this url no matter how it is submitted into the DB. This code allows you to get the query string variable that you are seeking...independent of how many variables exist. So this can be used if the full url is stored in the DB already and you need to get the ID to utilize on the site, or as I am using it, to grab the ID before it gets stored.
$url = "http://www.youtube.com/watch?v=P22G8YHveEg&feature=feedrec_grec_index"
// get the query string of the url
$query_string = parse_url($url, PHP_URL_QUERY); 
// parse out the query string into pieces
parse_str($query_string, $pieces);
// echo out the "v=" variable from the query string for storage in the DB and later use in my YouTube video plugin for WordPress
echo $pieces['v'];
// echos "P22G8YHveEg"

You can then take the "$pieces['v']" and store that in the DB. The enables you to embed the video, get its thumbnails and basically use it how like.
Post a comment
  1. Bobby

    Hi, Great article and thanks for sharing your knowledge on this. I have also done this in JavaScript as: function getYouTubeIdFromFullURL(queryString,url) { queryString = queryString.replace(/[[]/, "\[").replace(/[]]/, "\]"); var regex = new RegExp("[\?&]" + queryString + "=([^&#]*)"); var value = regex.exec(url); if (value == null) return ""; else return value[1]; } document.write(getYouTubeIdFromFullURL('v','http://www.youtube.com/watch?v=tIDh-O0-Apo&feature=pyv')); But the issue here is the following input, which is valid YouTube video: http://www.youtube.com/user/EASPORTS#p/c/228F559BC4A6D8BF http://www.youtube.com/v/bpJQZm_hkTE http://youtu.be/bpJQZm_hkTE Have you considered this?

    • Matthew Price

      Hi Bobby I have considered the other valid youtube urls. For the installation that i had for which i then wrote the article i was explicit for the users. Not a great solution, but it is still working. The backend users of the wordpress install were told what to grab, so they are "trained" as to what to grab. A good function would check the url for structure and then apply the correct methodology. Probably not too difficult, but would be a fun project. Thanks for the JS code. I am sure that will be helpful too Matt






Real Time Web Analytics ^