Next up in the PHP Helpers series is esc_html
:
[sourcecode lang=”php”]
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;
}
}
[/sourcecode]
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.
2 replies on “PHP Helpers: esc_html”
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.