取得 youtube id
youtube 現在分享網址有好多種,
可能是這樣:
可能是這樣:
https://www.youtube.com/watch?v=p_T3oNKjAT8
不確定User會填入哪一種分享網址的情況下,下面這方法可以解析出這些類型的 youtube id
- http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player
- http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player
- http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player
- http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
- http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
- http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
- http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
- http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player
試試看:
<?php /** * Get Youtube video ID from URL * * @param string $url * @return mixed Youtube video ID or FALSE if not found */ function getYoutubeIdFromUrl($url) { $parts = parse_url($url); if(isset($parts['query'])){ parse_str($parts['query'], $qs); if(isset($qs['v'])){ return $qs['v']; }else if(isset($qs['vi'])){ return $qs['vi']; } } if(isset($parts['path'])){ $path = explode('/', trim($parts['path'], '/')); return $path[count($path)-1]; } return false; } // Test $urls = array( 'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player', 'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player', 'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player', 'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player', 'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player', 'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player', 'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player', 'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player' ); foreach($urls as $url){ echo $url . ' : ' . getYoutubeIdFromUrl($url) . "\n"; }