以前曾经看到一个不错的文本转HTML的函数,可惜被我弄丢了。幸好还记得原理,今天决定自己写写。
在要使用的.aspx的@Page中加入 ValidateRequest="false",使用到的namespace:System.Text,System.Text.RegularExpressions。

/**/ /// <summary>
/// 将普通字符串格式化为HTML
/// </summary>
/// <param name="textStr">所要格式化的字符串</param>
/// <param name="spotUrlEmail">是否自动识别"http://"或"https://"开头的URL和Email地址,识别出来的URL和Email将会自动加上超链接</param>
/// <returns>格式化后的HTML代码</returns>
public static string TextToHTML(string textStr, bool spotUrlEmail)

{
StringBuilder html = new StringBuilder(textStr);

//html.Replace("&", "&"); //2006-4-26修改。不对"&"进行转义了,不然无法处理好多个QueryString的URL
html.Replace(" ", " "); //两个空格才转义,是为了较好处理带QueryString的URL后接空格的情况
html.Replace("<", "<");
html.Replace(">", ">");
html.Replace("\"", """);
html.Replace("\n", "<br />"); //IE中的换行为"\r\n",FF中为"\n"

if (spotUrlEmail)

{
int offset;

Regex linkRegex = new Regex("(http(s)?://)([\\w-]+\\.)+[\\w-]+(/[\\w-./?&%=]*)?");
MatchCollection linkMatches = linkRegex.Matches(html.ToString());
offset = 0;
foreach (Match match in linkMatches)

{

string linkHead = string.Format("<a href=\"
{0}\">", match.Value);

html.Insert(match.Index + offset, linkHead);
offset += linkHead.Length;

html.Insert(match.Index + match.Length + offset, "</a>");
offset += 4;
}

Regex emailRegex = new Regex("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
MatchCollection emailMatches = emailRegex.Matches(html.ToString());
offset = 0;
foreach (Match match in emailMatches)

{

string emailHead = string.Format("<a href=\"mailto:
{0}\">", match.Value);

html.Insert(match.Index + offset, emailHead);
offset += emailHead.Length;

html.Insert(match.Index + match.Length + offset, "</a>");
offset += 4;
}
}

return html.ToString();
}