开发者

What would be the most rational way to parse youtube video link for video ID in PHP? [duplicate]

开发者 https://www.devze.com 2023-04-11 20:28 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Youtube API - Extract video ID
This question already has answers here: Closed 11 years ago.

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?


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'];


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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消