Skip to content
← Back to Functions
Code

Email Normalization Validator

Trims, lowercases domain, validates format, and returns a normalized email value.

Function signature

ogNormalizeEmailAddress(email, lowercase_local_part = false)

Categories

  • Forms and Validation

Parameters

emailRaw email address.lowercase_local_partWhether to lowercase the mailbox/local part.

Return value

Short public-safe status message.

  • email
  • local_part
  • domain

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Trims, lowercases domain, validates format, and returns a normalized email value.
 *
 * Primary use case: Registration, login, contact forms.
 * Typical inputs: raw email string.
 * Typical output: normalized email or empty string.
 *
 * Implementation note: Do not lowercase the local part unless project policy allows it.
 *
 * @param string $email Raw email address.
 * @param bool $lowercase_local_part Whether to lowercase the mailbox/local part.
 * @return array Structured email normalization result.
 */
function ogNormalizeEmailAddress($email, $lowercase_local_part = false) {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array('email' => '')
	);

	$email = trim((string)$email);
	$email = str_replace(array("\r", "\n", "\t"), '', $email);
	if (empty($email)) {
		$result['message'] = 'Missing email address.';
		return $result;
	}

	$email = filter_var($email, FILTER_SANITIZE_EMAIL);
	if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
		$result['message'] = 'Invalid email address.';
		return $result;
	}

	$parts = explode('@', $email);
	if (count($parts) != 2) {
		$result['message'] = 'Invalid email address format.';
		return $result;
	}

	$local_part = $parts[0];
	$domain = strtolower($parts[1]);
	if (!empty($lowercase_local_part)) {
		$local_part = strtolower($local_part);
	}

	$email = $local_part . '@' . $domain;
	$result['success'] = true;
	$result['message'] = 'Email address normalized.';
	$result['data'] = array(
		'email' => $email,
		'local_part' => $local_part,
		'domain' => $domain
	);

	return $result;
}