esc_attr()WP 2.8.0

Escaping for HTML attributes. Converts <, >, &, ", ' characters to HTML entities. Does not make double escaping.

The function is intended to convert a raw string into a valid one for output in HTML attributes.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.17 sec (very fast) | PHP 7.2.5, WP 4.9.8
Hooks from the function

Return

String. Escaped string for use in HTML attributes.

Usage

<?php echo esc_attr( $text ) ?>
$text(string) (required)
Raw text for conversion.

Examples

1

#1 Example of double conversion

$text = "&gt; and &amp;";
echo esc_attr( $text );         // &gt; and &amp;
echo htmlspecialchars( $text ); // &amp;gt; and &amp;amp;
1

#2 Data cleaning on output

<?php $fname = ( isset( $_POST['fname'] ) ) ? $_POST['fname'] : ''; ?>
<input type="text" name="fname" value="<?php echo esc_attr( $fname ); ?>">
0

#3 Example of usage

Values parse examples:

var_dump( esc_attr( '0' ) );   // string(1) "0"
var_dump( esc_attr( 123 ) );   // string(3) "123"
var_dump( esc_attr( false ) ); // string(0) ""
var_dump( esc_attr( null ) );  // string(0) ""
var_dump( esc_attr( '' ) );    // string(0) ""
var_dump( esc_attr( '   ' ) ); // string(3) "   "
var_dump( esc_attr( [] ) );    // string(5) "Array" Notice: Array to string conversion in ...
$text = "<span>(tag) '(quote) \"(double quote) &(ampersand)";
echo esc_attr( $text );

// returns:
// &lt;span&gt;(tag) &#039;(quote) &quot;(double quote) &amp;(ampersand)

Changelog

Since 2.8.0 Introduced.

esc_attr() code WP 6.5.3

function esc_attr( $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 an HTML attribute.
	 *
	 * Text passed to esc_attr() is stripped of invalid or special characters
	 * before output.
	 *
	 * @since 2.0.6
	 *
	 * @param string $safe_text The text after it has been escaped.
	 * @param string $text      The text prior to being escaped.
	 */
	return apply_filters( 'attribute_escape', $safe_text, $text );
}