Format URLs in string to HTML Links in C#


/ Published in: C#

Will return a string that has any matched URLs wrapped in `<a>` tags.

Example: `"This is a link to http://foobar.com . Please visit !"`

Becomes: `"This is a link to <a href='http://foobar.com'>http://foobar.com</a> . Please visit!"`

Note: Opens links in new window.

Credit for regex:
[Faraz Shah Khan](http://weblogs.asp.net/farazshahkhan/archive/2008/08/09/regex-to-find-url-within-text-and-make-them-as-link.aspx "Credit")


Copy this code and paste it in your HTML
  1. public static string FormatUrls(string input) {
  2. string output = input;
  3. Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
  4.  
  5. MatchCollection mactches = regx.Matches(output);
  6.  
  7. foreach (Match match in mactches) {
  8. output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
  9. }
  10. return output;
  11. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.