The esc_html WordPress PHP filter is used to clean and escape a string for safe output in HTML.
Usage
$safe_text = apply_filters('esc_html', $safe_text, $text); // your custom code here
Parameters
$safe_text
: string – The text after it has been escaped.$text
: string – The text prior to being escaped.
More information
See WordPress Developer Resources: esc_html
Examples
Custom HTML escaping
Customize the HTML escaping by removing some special characters.
add_filter('esc_html', 'my_custom_esc_html', 10, 2); function my_custom_esc_html($safe_text, $text) { // Remove some special characters $special_chars = array('<', '>', '&'); $safe_text = str_replace($special_chars, '', $text); return $safe_text; }
Escape only specific characters
Escape only specific characters in a string.
add_filter('esc_html', 'escape_specific_chars', 10, 2); function escape_specific_chars($safe_text, $text) { // Escape only the characters '<' and '>' $safe_text = str_replace('<', '<', $text); $safe_text = str_replace('>', '>', $safe_text); return $safe_text; }
Allow specific HTML tags
Allow specific HTML tags to be displayed in the output.
add_filter('esc_html', 'allow_specific_html_tags', 10, 2); function allow_specific_html_tags($safe_text, $text) { $allowed_tags = array('<b>', '</b>', '<i>', '</i>'); $safe_text = strip_tags($text, implode('', $allowed_tags)); return $safe_text; }
Replace special characters with custom strings
Replace special characters with custom strings in the output.
add_filter('esc_html', 'replace_special_chars_with_custom_strings', 10, 2); function replace_special_chars_with_custom_strings($safe_text, $text) { $replace_pairs = array( '<' => '[lt]', '>' => '[gt]', '&' => '[amp]' ); $safe_text = strtr($text, $replace_pairs); return $safe_text; }
Add a prefix to the escaped text
Add a prefix to the escaped text to differentiate it from the original.
add_filter('esc_html', 'add_prefix_to_escaped_text', 10, 2); function add_prefix_to_escaped_text($safe_text, $text) { $prefix = 'escaped:'; return $prefix . $safe_text; }