Skip to content

Instantly share code, notes, and snippets.

@ps-team
Created October 27, 2017 08:06
Show Gist options
  • Save ps-team/9b41a7330729498a88d8f3dcb5cc08b3 to your computer and use it in GitHub Desktop.
Save ps-team/9b41a7330729498a88d8f3dcb5cc08b3 to your computer and use it in GitHub Desktop.
YouTube poster image RegEx. The following code strips the YouTube video ID from the url which is then used as a parameter to retrieve the video poster image. There are different sizes available e.g: http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg http://img.youtube.com…
@using System.Text.RegularExpressions;
@{
string image = String.Empty;
string youtubeid = string.Empty;
// Strip youtube id from the url so we can use it as a poster image
Regex regex = new Regex(@"^(?:https?\:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v\=))([\w-]{10,12})(?:$|\&|\?\#).*");
Match youtubeMatch = regex.Match("youtubeurl");
if (youtubeMatch.Success) {
youtubeid = youtubeMatch.Groups[1].Value;
image = "http://img.youtube.com/vi/" + youtubeid + "/0.jpg";
}
<img src="@image" alt="YouTube Poster Image" />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment