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.