Simple text to HTML conversion

前端 未结 6 769
醉梦人生
醉梦人生 2021-01-04 07:33

I have a very simple asp:textbox with the multiline attribute enabled. I then accept just text, with no markup, from the textbox. Is there a comm

6条回答
  •  渐次进展
    2021-01-04 08:20

    I know this is old, but I couldn't find anything better after some searching, so here is what I'm using:

    public static string TextToHtml(string text)
    {
        text = HttpUtility.HtmlEncode(text);
        text = text.Replace("\r\n", "\r");
        text = text.Replace("\n", "\r");
        text = text.Replace("\r", "
    \r\n"); text = text.Replace(" ", "  "); return text; }

    If you can't use HttpUtility for some reason, then you'll have to do the HTML encoding some other way, and there are lots of minor details to worry about (not just <>&).

    HtmlEncode only handles the special characters for you, so after that I convert any combo of carriage-return and/or line-feed to a BR tag, and any double-spaces to a single-space plus a NBSP.

    Optionally you could use a PRE tag for the last part, like so:

    public static string TextToHtml(string text)
    {
        text = "
    " + HttpUtility.HtmlEncode(text) + "
    "; return text; }

提交回复
热议问题