This code is a pretty old one, but I've been using it on our site and it works. It simply changes url and email into links and \n into <br />. If I don't allow the user to insert html then I send false into the allowHTML variable.
public static String ConvertToHTML(String text, bool allowHTML) {
StringBuilder sb = new StringBuilder(text);
if(!allowHTML) {
//Convert the brackets into HTML equivalents
sb.Replace("<","<") ;
sb.Replace(">",">") ;
//Convert the double quote
sb.Replace("\"",""");
}
string strInput = sb.Replace("\n", "<br />").ToString();
string strResult;
string strPattern = @"((([a-z0-9]+@))([a-z0-9]+(\-+[a-z0-9]+)*\.)+[a-z]{2,7}(/?\?([a-z0-9+_.%-]+)=[a-z0-9+_.%/-]*)?(&([a-z0-9+_.%-]+)=[a-z0-9+_.%/-]*)*/?)";
string strReplace = "<a href=\"mailto:$0\">$0</a>";
strResult = Regex.Replace(strInput, strPattern, strReplace, RegexOptions.IgnoreCase);
strPattern = @"((.){0,1}(http|ftp|https):\/\/|www\.)[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?";
strReplace = "<a href=\"$0\" target=\"_blank\">$0</a>";
strResult = Regex.Replace(strInput, strPattern, new MatchEvaluator(Util.CapText), RegexOptions.IgnoreCase);
return strResult;
}
public static string CapText(Match m) {
if (m.Value.ToLower().IndexOf("http://") > -1) {
if (m.Value.Substring(0, 1) != "\"" && m.Value.Substring(0, 1) != "=") {
if (m.Value.Substring(0, 1) == "h") {
return " <a href=\"" + m.Value + "\" target=\"_blank\">" + m.Value + "</a>";
} else {
return m.Value.Substring(0, 1) + " <a href=\"" + m.Value.Remove(0, 1) + "\" target=\"_blank\">" + m.Value.Remove(0, 1) + "</a>";
}
} else {
return m.Value;
}
} else {
return "<a href=\"http://" + m.Value + "\" target=\"_blank\">" + m.Value + "</a>";
}
}