PHP Helpers: esc_html

Next up in the PHP Helpers series is esc_html:

if ( !function_exists( 'esc_html' ) ) {
    function esc_html( $html, $char_set = 'UTF-8' ) {
        if ( empty( $html ) ) {
            return '';
        }

        $html = (string) $html;
        $html = htmlspecialchars( $html, ENT_QUOTES, $char_set );

        return $html;
    }
}

As you might have guessed this function escapes strings for HTML output. It’s not much more than a wrapper around htmlspecialchars, but provides central place to tweak your desired default behavior.

There’s room to experiment with additional optimizations and strict checking in this as well. I added the basics (look for empty strings, type cast to a string), if you’ve got a favorite additional check leave a comment below.

Related posts:

  1. PHP Helpers: html_print_r
  2. PHP Helpers: html_var_dump
  3. PHP Helpers: make_slug
  4. PHP Helpers: redirect_url
  5. PHP Helpers: debug_log

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>