Created
December 13, 2015 06:12
-
-
Save greenygh0st/0ebca53a90548ee15338 to your computer and use it in GitHub Desktop.
C# helper method for parsing out links and video (Vimeo & YouTube) content
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; | |
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