is there a Way to strip all Unnecessary MS Word Formatting from FCKEditor

user161433 picture user161433 · Aug 29, 2009 · Viewed 8k times · Source

I have installed fckeditor and when pasting from MS Word it adds alot of unnecessary formatting. I want to keep certain things like bold, italics, bulltes and so forth. I have searched the web and came up with solutions that strips everything away even the stuff that i wanted to keep like bold and italics. Is there a way to strip just the unnecessary word formatting?

Answer

Jack Mills picture Jack Mills · Apr 26, 2011

Just in case someone wants a c# version of the accepted answer:

public string CleanHtml(string html)
    {
        //Cleans all manner of evils from the rich text editors in IE, Firefox, Word, and Excel
        // Only returns acceptable HTML, and converts line breaks to <br />
        // Acceptable HTML includes HTML-encoded entities.

        html = html.Replace("&" + "nbsp;", " ").Trim(); //concat here due to SO formatting
        // Does this have HTML tags?

        if (html.IndexOf("<") >= 0)
        {
            // Make all tags lowercase
            html = Regex.Replace(html, "<[^>]+>", delegate(Match m){
                return m.ToString().ToLower();
            });
            // Filter out anything except allowed tags
            // Problem: this strips attributes, including href from a
            // http://stackoverflow.com/questions/307013/how-do-i-filter-all-html-tags-except-a-certain-whitelist
            string AcceptableTags = "i|b|u|sup|sub|ol|ul|li|br|h2|h3|h4|h5|span|div|p|a|img|blockquote";
            string WhiteListPattern = "</?(?(?=" + AcceptableTags + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>";
            html = Regex.Replace(html, WhiteListPattern, "", RegexOptions.Compiled);
            // Make all BR/br tags look the same, and trim them of whitespace before/after
            html = Regex.Replace(html, @"\s*<br[^>]*>\s*", "<br />", RegexOptions.Compiled);
        }


         // No CRs
         html = html.Replace("\r", "");
         // Convert remaining LFs to line breaks
         html = html.Replace("\n", "<br />");
         // Trim BRs at the end of any string, and spaces on either side
         return Regex.Replace(html, "(<br />)+$", "", RegexOptions.Compiled).Trim();
    }