» Birthday Bundle - Over $400 worth of Envato files for just $20
  Posts tagged 'e-mail'

How to extract username from an e-mail address string

Posted on September 5, 2008, Filled under PHP,  Bookmark it

If you need to extract the username from an e-mail address string then this snippet can help you. For instance, you can use this function inside a loop, while selecting emails from a database.

<?php
function getUsernameFromEmail($email)
{
$find = '@';
$pos = strpos($email, $find);

$username = substr($email, 0, $pos);

return $username;
}

$email = 'thecoder@domain.com';

$username = getUsernameFromEmail($email);

echo $username; // thecoder
?>

If, for any reason, you need to extract the domain from an e-mail address (or from multiple e-mail address that are in a database) then you can use this function:

<?php
function getDomainFromEmail($email)
{
// Get the data after the @ sign
$domain = substr(strrchr($email, "@"), 1);

return $domain;
}

// Example

$email = 'the_username_here@yahoo.com';

$domain = getDomainFromEmail($email);

echo $domain; // yahoo.com
?>

This function checks if an email address is valid or not. For example it is very useful if you have to validate a HTML form where someone should enter a real email address.

function ValidateEmail($email)
{
/*
(Name) Letters, Numbers, Dots, Hyphens and Underscores
(@ sign)
(Domain) (with possible subdomain(s) ).
Contains only letters, numbers, dots and hyphens (up to 255 characters)
(. sign)
(Extension) Letters only (up to 10 (can be increased in the future) characters)
*/

$regex = '/([a-z0-9_.-]+)'. # name

'@'. # at

'([a-z0-9.-]+){2,255}'. # domain & possibly subdomains

'.'. # period

'([a-z]+){2,10}/i'; # domain extension 

if($email == '') {
	return false;
}
else {
$eregi = preg_replace($regex, '', $email);
}

return empty($eregi) ? true : false;
}

$email = 'name@domain.com'; 

// will return true, since it matches the regex

if(ValidateEmail($email))
{
echo ''.$email.' is a valid e-mail address.';
}
else
{
echo ''.$email.' is not a valid e-mail address.';
}