In many web applications, it’s common to store and display user information, including the user’s name and email address. Often, you need to extract the user name from the email ID to personalize the user’s experience. In this tutorial you will learn how to extract the user name from an email ID using PHP with code example.
PHP Code to Extract User Name From Email ID
To extract the user name from an email ID in PHP, you can use the explode()
function with the “@” symbol as delimiter. Here’s is an example to extract the user name from an email ID:
function extractUserNameFromEmail($email) {
// Split the email address by "@" symbol
$parts = explode('@', $email);
// The user name is the first part of the split
$userName = $parts[0];
return $userName;
}
// Example usage
$email = "[email protected]";
$userName = extractUserNameFromEmail($email);
echo "User Name: " . $userName;
User Name: user
In this code, the extractUserNameFromEmail
function:
- takes an email address as input
- splits it using
explode('@', $email)
, - and returns the first part of the resulting array, which is the user name.
Keep in mind that this is a simple example that assumes the email address is well-formed and contains only one “@” symbol. You can add email validation before extracting the username:
// If the email is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// PHP code to extract username from email
}