Fun Infused Games  |   Smooth Operator RSS 

  Home   |    Archive   |    Subscribe   |    Search   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact and I will try and recover/find it.

Formatting Text For User Submitted Content
Date 9/18/2008    Tags    (0)

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 attacks).

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>");

        return myText;
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 place.

kick it on

This article has been view 961 times.


No comments for this article.

Add Comments

Name *
  Name the animal in the picture below:

Comment *
Insert Cancel

Xbox (1)  C# (14)  Visual Studio (1)  Cool (2)  iOS (3)  PC (1)  Rant (50)  Sports (11)  XBLIG (32)  Abduction Action (1)  Design (2)  Fin (1)  Volchaos (11)  VolChaos (1)  Nastier (4)  Game Dev (11)  Abdction Action! (1) (18)  Nasty (34)  SQL (1)  XNA (40)  World of Chalk (2)  Video Games (7)  Web (19)  Abduction Action! (27)  Hypership (28)  WP7 (8)  Advise (14)  FIN (20)  Trivia or Die (3)  Development (13)  Absurd (2)  Trivia Or Die (1)