18

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 common method by which line breaks and returns can be converted to <p> and <br/> tags?

I'm not looking for anything earth shattering, but at the same time I don't just want to do something like:

html.Insert(0, "<p>");
html.Replace(Enviroment.NewLine + Enviroment.NewLine, "</p><p>");
html.Replace(Enviroment.NewLine, "<br/>");
html.Append("</p>");

The above code doesn't work right, as in generating correct html, if there are more than 2 line breaks in a row. Having html like <br/></p><p> is not good; the <br/> can be removed.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Mark
  • 965
  • 2
  • 8
  • 12

7 Answers7

34

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", "<br>\r\n");
    text = text.Replace("  ", " &nbsp;");
    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 = "<pre>" + HttpUtility.HtmlEncode(text) + "</pre>";
    return text;
}
eselk
  • 6,764
  • 7
  • 60
  • 93
  • 1
    This should have been the accepted answer because surrounding text between PRE tags actually forces a double line, not a single line break. – Fandango68 Apr 24 '15 at 01:11
13

Your other option is to take the text box contents and instead of trying for line a paragraph breaks just put the text between PRE tags. Like this:

<PRE>
Your text from the text box...

and a line after a break...
</PRE>
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
8

Depending on exactly what you are doing with the content, my typical recommendation is to ONLY use the <br /> syntax, and not to try and handle paragraphs.

Mitchel Sellers
  • 62,228
  • 14
  • 110
  • 173
7

How about throwing it in a <pre> tag. Isn't that what it's there for anyway?

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
3

I know this is an old post, but I've recently been in a similar problem using C# with MVC4, so thought I'd share my solution.

We had a description saved in a database. The text was a direct copy/paste from a website, and we wanted to convert it into semantic HTML, using <p> tags. Here is a simplified version of our solution:

string description = getSomeTextFromDatabase();
foreach(var line in description.Split('\n')
{
    Console.Write("<p>" + line + "</p>");
}

In our case, to write out a variable, we needed to prefix @ before any variable or identifiers, because of the Razor syntax in the ASP.NET MVC framework. However, I've shown this with a Console.Write, but you should be able to figure out how to implement this in your specific project based on this :)

KGC
  • 131
  • 4
0

Combining all previous plus considering titles and subtitles within the text comes up with this:

public static string ToHtml(this string text)
{
    var sb = new StringBuilder();

    var sr = new StringReader(text);
    var str = sr.ReadLine();
    while (str != null)
    {
        str = str.TrimEnd();
        str.Replace("  ", " &nbsp;");
        if (str.Length > 80)
        {
            sb.AppendLine($"<p>{str}</p>");
        }
        else if (str.Length > 0)
        {
            sb.AppendLine($"{str}</br>");
        }
        str = sr.ReadLine();
    }

    return sb.ToString();
}

the snippet could be enhanced by defining rules for short strings

0

I understand that I was late with the answer for 13 years) but maybe someone else needs it

sample line 1 \r\n
sample line 2 (last at paragraph) \r\n\r\n [\r\n]+
sample line 3 \r\n

Example code

private static Regex _breakRegex = new("(\r?\n)+");
private static Regex _paragrahBreakRegex = new("(?:\r?\n){2,}");

public static string ConvertTextToHtml(string description) {
    string[] descrptionParagraphs = _paragrahBreakRegex.Split(description.Trim());
    if (descrptionParagraphs.Length > 0)
    {
        description = string.Empty;
        foreach (string line in descrptionParagraphs)
        {
            description += $"<p>{line}</p>";
        }
    }
    return _breakRegex.Replace(description, "<br/>");
}
TDG
  • 171
  • 1
  • 7