/// <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();
}