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#)

1690 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.
by Fandys    November 07, 2015 @ 12:17am

Thanks for sharing! It didn't work in all cases for example if I had in the text two links and second was part of first one e.g. "https://www.linksketch.com/b9-Y https://www.linksketch.com"<br /> so I modified it next way and it seems to work now :)<br /> <br /> public static string LinksAsHtml(this string text, string linkClasses = "external", string linkTarget = "_self")<br /> {<br /> var regProtocol = new Regex(@"(https?://)?");<br /> 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})");<br /> var regPort = new Regex(@"(:[0-9]{1,5})?");<br /> var regPath = new Regex(@"(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?");<br /> var regQuery = new Regex(@"(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?");<br /> var regFragment = new Regex(@"(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?");<br /> var regMain = new Regex("\\b" + regProtocol + regDomain + regPort + regPath + regQuery + regFragment + "(?=[?.!,;:\"]?([\\s]|$))");<br /> <br /> var results = regMain.Matches(text);<br /> var list = new List<string>();<br /> var matches = new List<Match>();<br /> <br /> int i = 0;<br /> Dictionary<string, string> uniqueStrings = new Dictionary<string, string>();<br /> <br /> foreach (Match item in results)<br /> {<br /> matches.Add(item);<br /> }<br /> <br /> foreach (Match match in matches.OrderByDescending(m => m.Length))<br /> {<br /> if (list.Contains(match.Value)) <br /> continue;<br /> list.Add(match.Value);<br /> <br /> string full = match.Value, friendly = full;<br /> if (string.IsNullOrEmpty(match.Groups[1].Value))<br /> full = "http://" + full;<br /> if (friendly.Length > 50)<br /> friendly = full.Substring(0, 25) + "..." + full.Substring(full.Length - 26);<br /> <br /> full = HttpUtility.HtmlEncode(full);<br /> friendly = HttpUtility.HtmlEncode(friendly);<br /> <br /> string link = string.Format(linkFormat, full, friendly, linkTarget, linkClasses);<br /> <br /> string uniqueString = "§||{{{%$#@>>>" + i + "<<<@#$%}}}||§";<br /> text = text.Replace(match.Value, uniqueString);<br /> uniqueStrings.Add(uniqueString, link);<br /> i++;<br /> }<br /> <br /> foreach (string s in uniqueStrings.Keys)<br /> {<br /> text = text.Replace(s, uniqueStrings[s]);<br /> }<br /> <br /> return text;<br /> }

by Fandys    November 07, 2015 @ 12:24am

OK, I see that pasting code into comment is working well so I made my own post: http://codepaste.net/2hd93i

Add a comment


Report Abuse
brought to you by:
West Wind Techologies