2

Possible Duplicates:
Youtube API - Extract video ID
How do I extract query parameters from an URL string in PHP?

If the input is as follows:

$input = 'http://www.youtube.com/watch?v=ALph_u2iee8&feature=topvideos_music';

And I want to end up with:

$result = 'ALph_u2iee8';

What would be the most rational way to do this in PHP?

Community
  • 1
  • 1
Frantisek
  • 7,485
  • 15
  • 59
  • 102
  • I vote no duplicate: this questions always has the same format, the other has multiple formats and parses the links from a string. This one is a much more concise question. – Levi Morrison Oct 10 '11 at 18:45
  • It is a duplicate. You (@Levi) should really post your answer in it. It's crazy to use a huge regular expression as the accepted answer suggests when PHP has easy to understand functions for the task. – Matthew Oct 10 '11 at 18:48
  • I repeat my stance: this is NOT a duplicate. That question deals with any format of youtube url, and this one deals with one format. Just because it is a subset question, it does not mean it deserves a subset or duplicate answer. There is a very tailored answer to this format specified. The mechanics are not even close to the same. – Levi Morrison Oct 11 '11 at 02:48

3 Answers3

11

PHP has functions to deal with this already.

$input = 'http://www.youtube.com/watch?v=ALph_u2iee8&feature=topvideos_music';

$queryString = parse_url($input, PHP_URL_QUERY);

$queries = array();

parse_str($queryString, $queries);

echo $queries['v'];
Levi Morrison
  • 19,116
  • 7
  • 65
  • 85
  • It's not really good practice to set variables in the local scope. I'd use the second parameter in that call to `parse_str()`. And of course, you could adjust the `parse_url()` and also check if the domain name matches. – Matthew Oct 10 '11 at 18:45
  • @Matthew I changed it as I agree with you. – Levi Morrison Oct 10 '11 at 18:55
0

Some will say to use a regex, but for something this simple, it is faster and better to go with subtrings.

This should do the job:

$input = 'http://www.youtube.com/watch?v=ALph_u2iee8&feature=topvideos_music';
$start = strpos($input, '?v=');
$length = strpos($input, '&', $start + 1) - $start;
echo substr($input, $start + 3, $length);

Of course, the parse_url/parse_str is the correct way.

Mamsaac
  • 6,173
  • 3
  • 21
  • 30
0

I use this function when I'm trying to grab a youtube video ID from a URL

function get_youtube_id_from_url( $url ) {
    preg_match('/[\\?&]v=([^&#]*)/si', $url, $matches );

    return !empty( $matches ) ? $matches[1] : false;
}
Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108