wpseek.com
A WordPress-centric search engine for devs and theme authors



sanitize_email › WordPress Function

Since1.5.0
Deprecatedn/a
sanitize_email ( $email )
Parameters:
  • (string) $email Email address to sanitize.
    Required: Yes
Returns:
  • (string) The sanitized email address, or an empty string if invalid.
Defined at:
Codex:
Change Log:
  • 7.1.0

Sanitizes an email address.

Strips stray whitespace from the input, then strips trailing dots from the domain. This is designed to recover from cut/paste mistakes without any risk of transforming the input into a different address than the user intended. Validation and final form are determined by the 'sanitize_email' filter; the default filter is registered in default-filters.php and delegates to WP_Email_Address::from_string.


Source

function sanitize_email( $email ) {
	// Strip surrounding whitespace.
	$email = trim( $email );

	// Extract the address from "Display Name <username@domain>" format.
	if ( 1 === preg_match( '/<([^>]+)>$/', $email, $matches ) ) {
		$email = $matches[1];
	}

	/*
	 * Strip soft hyphens and whitespace adjacent to structural separators (dots and @),
	 * e.g. copy-paste artifacts like "info@example\u{00AD}.com" or "info@example .com".
	 *
	 * In some cases, e.g. autocorrect, some older software has been seen to add the
	 * space for unrecognized TLDs. This re-joins the parts for proper examination.
	 */
	$email = preg_replace( '/[\x{00AD}\s]*([.@])[\x{00AD}\s]*/u', '$1', $email ) ?? $email;

	// Strip a trailing dot from the domain (e.g. if pasted from the end of a sentence).
	if ( str_contains( $email, '@' ) ) {
		list( $local, $domain ) = explode( '@', $email, 2 );
		$domain                 = rtrim( $domain, '.' );
		$email                  = $local . '@' . $domain;
	}

	/**
	 * Filters a sanitized email address.
	 *
	 * Filters registered on this hook perform the actual validation and return
	 * the canonical email string on success or an empty string on failure.
	 * The default filter is registered in default-filters.php.
	 *
	 * @since 2.8.0
	 *
	 * @param string      $sanitized_email The sanitized email address, or empty string.
	 * @param string      $email           The email address as provided to sanitize_email().
	 * @param string|null $context         Validation context, or null for the initial call.
	 */
	return apply_filters( 'sanitize_email', '', $email, null );
}