Created
June 27, 2016 10:32
-
-
Save svrooij/dc840d97e4cfa91cc6e09ea7da86207b to your computer and use it in GitHub Desktop.
Youtube link to Embed code in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text.RegularExpressions; | |
namespace YourNamespace | |
{ | |
internal static class StringExtensions | |
{ | |
//http://stackoverflow.com/questions/3652046/c-sharp-regex-to-get-video-id-from-youtube-and-vimeo-by-url | |
static readonly Regex YoutubeVideoRegex = new Regex(@"youtu(?:\.be|be\.com)/(?:(.*)v(/|=)|(.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase); | |
static readonly Regex VimeoVideoRegex = new Regex(@"vimeo\.com/(?:.*#|.*/videos/)?([0-9]+)", RegexOptions.IgnoreCase | RegexOptions.Multiline); | |
// Use as | |
// string youtubeLink = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; | |
// var embedCode = youtubeLink.UrlToEmbedCode(); | |
static internal string UrlToEmbedCode(this string url) | |
{ | |
if (!string.IsNullOrEmpty(url)) | |
{ | |
var youtubeMatch = YoutubeVideoRegex.Match(url); | |
if (youtubeMatch.Success) | |
{ | |
return getYoutubeEmbedCode(youtubeMatch.Groups[youtubeMatch.Groups.Count - 1].Value); | |
} | |
var vimeoMatch = VimeoVideoRegex.Match(url); | |
if (vimeoMatch.Success) | |
{ | |
return getVimeoEmbedCode(vimeoMatch.Groups[1].Value); | |
} | |
} | |
return null; | |
} | |
const string youtubeEmbedFormat = "<iframe type=\"text/html\" class=\"embed-responsive-item\" src=\"https://www.youtube.com/embed/{0}\"></iframe>"; | |
private static string getYoutubeEmbedCode(string youtubeId) | |
{ | |
return string.Format(youtubeEmbedFormat, youtubeId); | |
} | |
const string vimeoEmbedFormat = "<iframe src=\"https://player.vimeo.com/video/{0}\" class=\"embed-responsive-item\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"; | |
private static string getVimeoEmbedCode(string vimeoId) | |
{ | |
return string.Format(vimeoEmbedFormat, vimeoId); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't make sense as an extension method for the string class