Turns funky characters into HTML entity equivalents e.g. - Java java.lang

Java examples for java.lang:char

Description

Turns funky characters into HTML entity equivalents e.g.

Demo Code


import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class Main{
    private static Map i2e = new HashMap();
    /**//from   www  .  ja v a 2s .co m
     * Turns funky characters into HTML entity equivalents<p>e.g. <tt>"bread" & "butter"</tt> =>
     * <tt>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</tt>. Update: supports nearly all HTML
     * entities, including funky accents. See the source code for more detail.</p>
     *
     * @param source String to escape
     *
     * @return Escaped string
     */
    public static String htmlEscape(String source) {

        StringBuffer buf = new StringBuffer();

        int i;

        for (i = 0; i < source.length(); ++i) {

            char ch = source.charAt(i);

            String entity = (String) i2e.get(new Integer((int) ch));

            if (entity == null) {

                if (((int) ch) > 128) {

                    buf.append("&#" + ((int) ch) + ";");

                } else {

                    buf.append(ch);

                }

            } else {

                buf.append("&" + entity + ";");

            }

        }

        return buf.toString();

    }
}

Related Tutorials