eight / solution 8.1
<?php
function verifyEmail(string $e)
{
// check for basic pattern ([email protected])
if (!preg_match("/.+@.+\..+/", $e)) {
return false;
}
// convert to lowercase
$e = mb_convert_case($e, MB_CASE_LOWER);
// eliminate whitespace
$e = preg_replace("/\s+/", "", $e);
// simplify consecutive periods
$e = preg_replace("/\.+/", ".", $e);
// split email into name and domain because their constraints are different
$name = explode("@", $e)[0];
$domain = explode("@", $e)[1];
// check for both elements
if (!strlen($name) || !strlen($domain)) {
return false;
}
// remove leading/trailing periods
$name = trim($name, ".");
$domain = trim($domain, ".");
// remove invalid characters from both sections
$name = preg_replace("/[^a-z0-9!#%\$&\'\*\+\-\/\=\?\^_`\{|\}~\.]/", "", $name);
$domain = preg_replace("/[^a-z0-9\-\.]/", "", $domain);
// crop name to 64 characters
$name = substr($name, 0, 64);
// crop each domain segment to 63 characters
$domain = explode(".", $domain);
foreach ($domain as &$i) {
$i = substr($i, 0, 63);
}
$domain = implode(".", $domain);
// check for both elements again (in case all characters were invalid)
if (!strlen($name) || !strlen($domain)) {
return false;
}
// rebuild email
$e = $name . "@" . $domain;
return $e;
}
print_r(verifyEmail(" a GJF [email protected]. ") . "\n");