Convert plain text to HTML

I have a very simple asp:textbox with the multiline attribute enabled. Then I accept the text, without markup, from the text box. Is there a general method by which line breaks and return values ​​can be converted to <p> and <br/> tags?

I am not looking for anything destructive, but at the same time I do not 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 does not work correctly, as when generating the correct html, if the line has more than two line breaks. Having html like <br/></p><p> not good; <br/> can be deleted.

+7
html c # parsing
source share
5 answers

Depending on what you do with the content, my typical recommendation is to ONLY use the <br /> syntax, rather than trying to process paragraphs.

+3
source share

I know this is old, but after some searching, I could not find anything better, so here is what I use:

 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 for some reason you cannot use HttpUtility, you will have to do HTML encoding in a different way, and there are a lot of small details to worry about (and not just <>& ).

HtmlEncode only processes special characters, so after that I convert any combination of carriage return and / or line to BR tag and any double spaces to single space plus NBSP.

If desired, you can use the PRE tag for the last part, for example:

 public static string TextToHtml(string text) { text = "<pre>" + HttpUtility.HtmlEncode(text) + "</pre>"; return text; } 
+21
source share

Another option is to take the contents of the text field and, instead of trying to use a paragraph line, simply puts the text between the PRE tags. Like this:

 <PRE> Your text from the text box... and a line after a break... </PRE> 
+10
source share

How to throw it in the <pre> . Isn't that what it is?

+4
source share

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

We had a description stored in the database. The text was a direct copy / paste from the website, and we wanted to convert it to 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 a variable, we needed the @ prefix before any variable or identifiers due to the Razor syntax in the ASP.NET MVC structure. However, I showed this with Console.Write , but you have to figure out how to implement this in your specific project based on this :)

+3
source share

All Articles