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 kriswd40@yahoo.com and I will try and recover/find it.

Formatting Text For User Submitted Content
Date 9/18/2008    Tags ASP.net    (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 DotNetKicks.com



This article has been view 961 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel


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