Formatting Text For User Submitted Content
When displaying user generated content on a webpage, such as comments, you often want to allow your users to do things like page breaks, bold text, and
italic text. You don't want them to have to use HTML to do so (or at least you shouldn't want to, as this opens your site up for cross-site scripting
It just so happens that I have created a basic format function that does just that. First this function converts anything HTML into a safe display format
(so that if you enter code to create something like a table, you'll just see the text <table> instead of the actual table). Next I insert <br /> tags for
new line characters so that new lines are preserved exactly how the user types them in.
Finally I added some replaces for [B],[I], ect. so the user can have bold and italic text in their post.
public string FormatText(string myText)
// Remove/format HTML
myText = HttpContext.Current.Server.HtmlEncode(myText);
// Replace end of line with <BR> tags.
myText = myText.Replace(Environment.NewLine, "<br />");
// Special formatting
myText = myText.Replace("[b]", "<b>");
myText = myText.Replace("[/b]", "</b>");
myText = myText.Replace("[B]", "<b>");
myText = myText.Replace("[/B]", "</b>");
myText = myText.Replace("[i]", "<i>");
myText = myText.Replace("[/i]", "</i>");
myText = myText.Replace("[I]", "<i>");
myText = myText.Replace("[/I]", "</i>");
If you want to be really nice to your user, you can allow them to enter things like links using regular expressions or include a whole set of
smileys using a simple replace. I may expand on this example in the future and do just that.
Also of note, while this code takes care of displaying HTML on your page, you probably shouldn't allow users to save HTML to your database in the first
This article has been view 961 times.