sanitize_user()WP 2.0.0

Cleans the username (login, username) by removing unsafe characters.

Removes: html tags, notes, html entities, and other characters not included in ASCII.

Hooks from the function

Returns

String. Cleaned username.

Usage

sanitize_user( $username, $strict );
$username(string) (required)
The username to be cleaned.
$strict(boolean)
If set to true, non-standard characters in the name will be removed. Only characters^ a-z 0-9 _ . - @ will be allowed in names. Note that only the English alphabet is available.
Default: false

Examples

0

#1 An example of how the user name filtering function works:

$string = '     Leonid-{?}[]<tag>rus_yo`@';

echo sanitize_user( $string ); //> Leonid-{?}[]rus_yo`@

echo sanitize_user( $string, 1 ); //> Leonid-_

Changelog

Since 2.0.0 Introduced.

sanitize_user() code WP 6.8.3

function sanitize_user( $username, $strict = false ) {
	$raw_username = $username;
	$username     = wp_strip_all_tags( $username );
	$username     = remove_accents( $username );
	// Remove percent-encoded characters.
	$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
	// Remove HTML entities.
	$username = preg_replace( '/&.+?;/', '', $username );

	// If strict, reduce to ASCII for max portability.
	if ( $strict ) {
		$username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
	}

	$username = trim( $username );
	// Consolidate contiguous whitespace.
	$username = preg_replace( '|\s+|', ' ', $username );

	/**
	 * Filters a sanitized username string.
	 *
	 * @since 2.0.1
	 *
	 * @param string $username     Sanitized username.
	 * @param string $raw_username The username prior to sanitization.
	 * @param bool   $strict       Whether to limit the sanitization to specific characters.
	 */
	return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
}