1

I'm using Android Youtube API v3. My application plays youtube video. I want to get videoID from youtube url.
I see there are a lot of sample that uses pattern to parse the url to get the video ID.
But I'm afraid of this way will fail when youtube change their url in the future.
There are some formats of youtube video url:

http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg

Are there any API to get video ID from the url?
Thanks in advance.

Huy Duong Tu
  • 7,798
  • 5
  • 25
  • 46

2 Answers2

1

Yes, as you already figured this out that it is not that simple to get the video ID of a youtube video because of the inconsistency. You need to include all the possible permutations and combinations in the PHP (or what ever language script) you are going to parse the URL using regular expressions.

This question has been asked previously on SO you can refer that and add your own logic to parse the URL. I am pasting the links of some of them:

Youtube API - Extract video ID

how to get youtube video id from url

JavaScript REGEX: How do I get the YouTube video id from a URL?

https://halgatewood.com/php-get-the-youtube-video-id-from-a-youtube-url

http://www.microtuts.com/c-get-youtube-video-id-from-url-with-regex/

Community
  • 1
  • 1
AniV
  • 3,997
  • 1
  • 12
  • 17
0

It will return you the video id: watchLink ="https://www.youtube.com/watch?v=s6RPsaco-vA"

 public static String getVideoId(String watchLink){

     return watchLink.substring(watchLink.length() - 11);
}
pavel
  • 1,603
  • 22
  • 19
  • 1
    There're many links I listed above. Some of them, the video Id isn't be at the end of link. Therefore, your solution doesn't work – Huy Duong Tu Apr 25 '16 at 03:04
  • Just run this code into your java IDE or Android IDE it will return this s6RPsaco-vA package abas.a.a.time; public class YoutubeLink { public static final String link = "https://www.youtube.com/watch?v=s6RPsaco-vA"; public static void main(String[] args) { String Youtubelink = getVideoId(link); System.out.println(Youtubelink); } public static String getVideoId(String watchLink){ return watchLink.substring(watchLink.length() - 11); } } – pavel Apr 25 '16 at 08:42