Skip to content

Instantly share code, notes, and snippets.

@svrooij
Created June 27, 2016 10:32
Show Gist options
  • Save svrooij/dc840d97e4cfa91cc6e09ea7da86207b to your computer and use it in GitHub Desktop.
Save svrooij/dc840d97e4cfa91cc6e09ea7da86207b to your computer and use it in GitHub Desktop.
Youtube link to Embed code in C#
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);
}
}
}
@Cloudmersive
Copy link

This doesn't make sense as an extension method for the string class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment