Skip to content

PHP Helpers: esc_html

19 Jan 2010

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 Tip: Spaces Are Not empty()
  4. PHP Helpers: make_slug
  5. PHP Helpers: redirect_url

From → Posts

2 Comments
  1. These are great, I have always had one that I used called pre_dump, which was var_dump wrapped in PRE tags and several others that I use for debugging purposes.

    I recently decided to test yours out, and ran into at least 1 thing that would help me, which is to rename esc_html to something else. I have always used auto_prepend_file to include these common helpers, and when doing so it of course conflicts with my WordPress install.

    Also, and this is just me wanting to type less but, I think that html_print_r and html_var_dump should echo rather than return.

    I know this wasn’t really designed for my specific use case, but it does perform this job well.

    In any case, thank you for these, it will surely help me out.

    • For html_print_r and html_var_dump, I did the same thing for my local code, they echo by default. After more thought it seemed like the right thing to do.

      I’m not sure exactly what the right answer is for using these in a WordPress context. Perhaps load them as a plugin and keep the conditional checks for function name collisions?

      Thanks for the feedback.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS