esc_html()WP 2.8.0

Escaping for HTML blocks. Converts <, >, &, ", ' characters to HTML entities.

Character Replacement
& (Ampersand) &amp;
" (Double Quote) &quot;
' (Single Quote) &#039;
< (Less-than) &lt;
> (Greater-than) &gt;

The function also checks the text for an incorrect UTF-8 encoding and, if possible, fixes it.

If you need, on the contrary, decode the text: from HTML entities into characters, use wp_specialchars_decode()

If we pass an array to this function, the array will be destroyed:

$arr = array( 5, 6 );
$arr = esc_html( $arr ); // $arr is a string "Array"

The function is based on htmlspecialchars() and changes its default parameters, so htmlspecialchars() makes double encoding and esc_html() doesn't:

echo esc_html( '& - &amp;' );         //> &amp; - &amp;
echo htmlspecialchars( '& - &amp;' ); //> &amp; - &amp;amp;

esc_html() is a replacement for deprecated function wp_specialchars().

1 time — 0.000037 sec (very fast) | 50000 times — 0.27 sec (very fast) | PHP 7.0.2, WP 4.4.1
Hooks from the function

Return

String. Converted text.

Usage

esc_html( $text );
$text(string) (required)
Raw text for conversion.

Examples

0

#1 Simple example

$text = "<p><b> This \"Makes Sense\" & 'Makes Sense'!</b></p>";
echo esc_html( $text );

/* result:
&lt;p&gt;&lt;b&gt; This &quot;Makes Sense&quot; &amp; &#039;Makes Sense&#039;!&lt;/b&gt;&lt;/p&gt;
*/

Changelog

Since 2.8.0 Introduced.

esc_html() code WP 6.7.1

function esc_html( $text ) {
	$safe_text = wp_check_invalid_utf8( $text );
	$safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
	/**
	 * Filters a string cleaned and escaped for output in HTML.
	 *
	 * Text passed to esc_html() is stripped of invalid or special characters
	 * before output.
	 *
	 * @since 2.8.0
	 *
	 * @param string $safe_text The text after it has been escaped.
	 * @param string $text      The text prior to being escaped.
	 */
	return apply_filters( 'esc_html', $safe_text, $text );
}