sanitize_user() WordPress Function

The sanitize_user() function is a WordPress utility function that handles the cleaning and sanitizing of a username. It is used when a user is registering with WordPress or when a user is updating their profile.

sanitize_user( string $username, bool $strict = false ) #

Sanitizes a username, stripping out unsafe characters.


Description

Removes tags, octets, entities, and if strict is enabled, will only keep alphanumeric, _, space, ., -, @. After sanitizing, it passes the username, raw username (the username in the parameter), and the value of $strict as parameters for the ‘sanitize_user’ filter.


Top ↑

Parameters

$username

(string)(Required)The username to be sanitized.

$strict

(bool)(Optional) If set limits $username to specific characters.

Default value: false


Top ↑

Return

(string) The sanitized username, after passing through filters.


Top ↑

Source

File: wp-includes/formatting.php

function sanitize_user( $username, $strict = false ) {
	$raw_username = $username;
	$username     = wp_strip_all_tags( $username );
	$username     = remove_accents( $username );
	// Kill octets.
	$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
	// Kill 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 );
}


Top ↑

Changelog

Changelog
VersionDescription
2.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More