Inclusion of htmlSpecialChars method

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Inclusion of htmlSpecialChars method

John Martin
I'm looking to include a new method htmlSpecialChars into the
StringUtil class and am looking for feedback.

While working on the DHL enhancement, I found the need for a method
similar to the PHP function htmlSpecialChars which allows you to
output HTML and XML to the browser so that it can be viewed.  When
there are errors, the XML is being output to the screen but the
special chars ( <, >, &, ", and ' ) are not displayed.

Another purpose for this function is to safeguard user input that is
later displayed in the browser.

Here is a link to docs on the PHP function  http://us3.php.net/htmlspecialchars.

Here's my implementation:

    /**
     * Translates various HTML characters in a string so that the
string can be displayed in a browser safely
     * <p>
     * This function is useful in preventing user-supplied text from
containing HTML markup, such as in a message board or
     * guest book application. The optional arguments doubleQuotes and
singleQuotes allow the control of the substitution of
     * the quote characters.  The default is to translate them with
the HTML equivalent.
     * </p>
     * The translations performed are: <ol>
     *    <li>'&' (ampersand) becomes '&amp;'
     *    <li>'"' (double quote) becomes '&quot;' when doubleQuotes is true.
     *    <li>''' (single quote) becomes '&#039;' when singleQuotes is true.
     *    <li>'<' (less than) becomes '&lt;'
     *    <li>'>' (greater than) becomes '&gt;'
     *    <li>\n (Carriage Return) becomes '&lt;br&gt;gt;'
     * </ol>
     */
    public static String htmlSpecialChars(String html, boolean
doubleQuotes, boolean singleQuotes, boolean insertBR) {
        html = StringUtil.replaceString(html, "&", "&amps;");
        html = StringUtil.replaceString(html, "<", "&lt;");
        html = StringUtil.replaceString(html, ">", "&gt;");
        if (doubleQuotes) {
            html = StringUtil.replaceString(html, "\"", "&quot;");
        }
        if (singleQuotes) {
            html = StringUtil.replaceString(html, "'", "&#039");
        }
        if (insertBR) {
            html = StringUtil.replaceString(html, "\n", "<br>");
        }

        return html;
    }
    public static String htmlSpecialChars(String html) {
        return htmlSpecialChars(html, true, true, true);
    }

Thanks,

John