tags:

views:

326

answers:

3

Forgive me for the beginner regex question but I was hoping that someone could show me how to get the youtube id out of a url regardless of what other GET variables are in the URL.

Use this video for example:

http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related

so between v= and before the next &

+2  A: 
if (preg_match('![?&]{1}v=([^&]+)!', $url . '&', $m))
    $video_id = $m[1];
NullUserException
Peter Ajtai
@Peter : Fixed.
NullUserException
+5  A: 

Use parse_url() and parse_str().

(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)

parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY.

Now we have the query, which is v=C4kxS1ksqtw&feature=relate, but we only want the part after v=. For this we turn to parse_str which basically works like GET on a string. It takes a string and creates the variables specified in the string. In this case $v and $feature is created. We're only interested in $v.

Putting everything together, we have:

<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&amp;feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ) );
echo $v;    
  // Output: C4kxS1ksqtw
?> 

Edit:

hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:

Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.Jamie Zawinski

Peter Ajtai
Although it doesn't use regex (at least visibly - I'm not sure how `parse_url()` works under the hood), this is the way to go.
Thomas Owens
<Insert Zawinski Quote Here>. Though in all seriousness, using language functions to perform a task is frequently going to be better than the hoop jumping that a good regex can require.
Charles
haha thanks guys :)
Wes
I'd only suggest using parse_str()'s second parameter to store the query params in an array. Having variables magically appear out of thin air is never a good idea.
mellowsoon
A quick simple example of why using parse_str()'s "magic variables" isn't a good idea -> http://pastebin.com/AtaaPH4r
mellowsoon
@mello - Good suggestion.
Peter Ajtai
A: 

(?<=\?v=)([a-zA-Z0-9_-]){11}

this should do it as well.

kyri