public static String escapeHtml ( String htmlString ) { StringBuffer sb = new StringBuffer ( htmlString . length ( ) ) ; // true if last char was blank boolean lastWasBlankChar = false ; int len = htmlString . length ( ) ; char c ; for ( int i = 0 ; i < len ; i ++ ) { c = htmlString . charAt ( i ) ; if ( c == ' ' ) { // blank gets extra work, // this solves the problem you get if you replace all // blanks with &nbsp;, if you do that you loss // word breaking if ( lastWasBlankChar ) { lastWasBlankChar = false ; sb . append ( "&nbsp;" ) ; } else { lastWasBlankChar = true ; sb . append ( ' ' ) ; } } else { lastWasBlankChar = false ; // // HTML Special Chars if ( c == ' ' ) sb . append ( "&quot;" ) ; else if ( c == ' ' ) sb . append ( "&amp;" ) ; else if ( c == ' ' ) sb . append ( "&lt;" ) ; else if ( c == ' ' ) sb . append ( "&gt;" ) ; else if ( c == ' ' ) sb . append ( "-" ) ; else if ( c == ' ' ) sb . append ( "-" ) ; else if ( c == ' ' ) // Handle Newline sb . append ( "&lt;br/&gt;" ) ; else { int ci = 0xffff & c ; if ( ci < 160 ) // nothing special only 7 Bit sb . append ( c ) ; else { // Not 7 Bit use the unicode system sb . append ( "&#" ) ; sb . append ( String . valueOf ( ci ) ) ; sb . append ( ' ' ) ; } } } } return sb . toString ( ) ; }
Escape html special chars from string