$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.
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.