// Converts single line breaks to BR tags, multiple line breaks to P tags. Does nothing more.
public static string PlainTextToHtml(string text)
{
if (string.IsNullOrWhiteSpace(text)) return text?.Trim();
text = text.Trim();
// Remove blanks from otherwise completely empty lines.
text = Regex.Replace(text, @"^\s+$", string.Empty, RegexOptions.Multiline);
text = text.Replace("\r\n", "\r");
text = text.Replace("\n", "\r");
text = text.Replace("\r", "\r\n");
// Codense multiple blank lines.
text = Regex.Replace(text, "\n{3,}", Environment.NewLine + Environment.NewLine);
text = HttpUtility.HtmlEncode(text);
text = text.Replace("\r\n", "\r");
text = text.Replace("\n", "\r");
text = text.Replace("\r\r", @"</p><p>");
text = text.Replace("\r", @"<br>");
text = @"<p>" + text + @"</p>";
return text;
}
Comments