CodePaste Logo
New Snippet New Recent Snippets Recent Snippets My Snippets My Snippets My Favorites Favorites Web Code Search Snippets Search
Sign inor Register
Language: csharp

Replace URLs in text with HTML links (PHP -> C#)

1035 Views   
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; namespace System.Text { public static class StringTransformer { static readonly string linkFormat = "<a href=\"{0}\" title=\"{0}\" target=\"{2}\" class=\"{3}\">{1}</a>"; /// <summary> /// Replaces all URLs in a string with HTML links. /// </summary> /// <param name="text"></param> /// <param name="linkClasses"></param> /// <param name="linkTarget"></param> /// <returns></returns> public static string LinksAsHtml(this string text, string linkClasses = "external", string linkTarget = "_self") { var regProtocol = new Regex(@"(https?://)?"); var regDomain = new Regex(@"((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})"); var regPort = new Regex(@"(:[0-9]{1,5})?"); var regPath = new Regex(@"(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?"); var regQuery = new Regex(@"(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?"); var regFragment = new Regex(@"(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?"); var regMain = new Regex("\\b" + regProtocol + regDomain + regPort + regPath + regQuery + regFragment + "(?=[?.!,;:\"]?([\\s]|$))"); var results = regMain.Matches(text); var list = new List<string>(); var matches = new List<Match>(); foreach (Match item in results) { matches.Add(item); } foreach (Match match in matches.OrderByDescending(m => m.Length)) { if (list.Contains(match.Value) || list.Any(s => s.Contains(match.Value))) continue; list.Add(match.Value); string full = match.Value, friendly = full; if (string.IsNullOrEmpty(match.Groups[1].Value)) full = "http://" + full; if (friendly.Length > 50) friendly = full.Substring(0, 25) + "..." + full.Substring(full.Length-26); full = HttpUtility.HtmlEncode(full); friendly = HttpUtility.HtmlEncode(friendly); string link = string.Format(linkFormat, full, friendly, linkTarget, linkClasses); text = text.Replace(match.Value, link); } return text; } } }
by SandRock
  January 20, 2012 @ 11:21am
Tags:
Description:
In response to http://stackoverflow.com/questions/1188129/replace-urls-in-text-with-html-links<br /> This is a similar implementation using C#.<br /> You can freely use this code. Please use the stackoverflow topic for suggestions and comments.
Add a comment


Report Abuse
brought to you by:
West Wind Techologies