Return to Snippet

Revision: 12577
at April 14, 2009 18:06 by jasonseney


Updated Code
public static string FormatUrls(string input) {
	string output = input;
	Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);

	MatchCollection mactches = regx.Matches(output);

	foreach (Match match in mactches) {
		output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
	}
	return output;
}

Revision: 12576
at March 19, 2009 17:22 by jasonseney


Initial Code
public static string FormatUrls(string input) {
	string output = input;
	Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

	MatchCollection mactches = regx.Matches(output);

	foreach (Match match in mactches) {
		output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
	}
	return output;
}

Initial URL

                                

Initial Description
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")

Initial Title
Format URLs in string to HTML Links in C#

Initial Tags
regex, url, c

Initial Language
C#