Skip to content

Instantly share code, notes, and snippets.

@greenygh0st
Created December 13, 2015 06:12
Show Gist options
  • Save greenygh0st/0ebca53a90548ee15338 to your computer and use it in GitHub Desktop.
Save greenygh0st/0ebca53a90548ee15338 to your computer and use it in GitHub Desktop.
C# helper method for parsing out links and video (Vimeo & YouTube) content
using System;
using System.Text.RegularExpressions;
namespace DalesLab.Helpers
{
public static class Parser
{
public static readonly Regex VimeoVideoRegex = new Regex(@"vimeo\.com/(?:.*#|.*/videos/)?([0-9]+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
public static readonly Regex YoutubeVideoRegex = new Regex(@"youtu(?:\.be|be\.com)/(?:(.*)v(/|=)|(.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase);
public static readonly Regex HyperlinkRegex = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase); //http://weblogs.asp.net/farazshahkhan/regex-to-find-url-within-text-and-make-them-as-link
public static string ParseLinks(string str)
{
//here we pass through all of the regex
MatchCollection HyperLinkmatches = HyperlinkRegex.Matches(str);
foreach (Match match in HyperLinkmatches)
{
Match youtubeMatch = YoutubeVideoRegex.Match(match.Value);
Match vimeoMatch = VimeoVideoRegex.Match(match.Value);
if (youtubeMatch.Success)
{
var id = youtubeMatch.Groups[1].Value;
str = str.Replace(match.Value, "<iframe id=\"ytplayer\" type=\"text/html\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/"+id+"\" frameborder=\"0\"/>");
}else if (vimeoMatch.Success)
{
var id = vimeoMatch.Groups[1].Value;
str = str.Replace(match.Value, "<iframe src=\"//player.vimeo.com/video/"+id+"\" width=\"WIDTH\" height=\"HEIGHT\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>");
}else
{
str = str.Replace(match.Value, "<a target='_blank' href='" + match.Value + "'>" + match.Value + "</a>");
}
}
return str;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment