How to extract the user name from the email ID using PHP ? (original) (raw)

Last Updated : 26 May, 2021

Given a string email address, extract the username.

Input:priyank@geeks.comOutput: priyank

Input:princepriyank@gfg.comOutput: princepriyank

Approach 1: Using PHP strstr() to extract the username from the email address.

In this, “@” symbol is the separator for the domain name and user name of the email address. The strstr() PHP function is used to search for the first occurrence of a string i.e. "@" inside another string i.e. email address to get the username as result.

Example:

PHP `

username=strstr(username = strstr(username=strstr(email, '@', true); // Display the username echo $username."\n"; ?>

`

Approach 2: Using PHP explode() function.

In this, we harness the fact that the “@” symbol is the separator for the domain name and user name of the email address. So explode() is used to break a string into an array by a separator "@".

Example:

PHP `

parts=explode("@",parts = explode("@",parts=explode("@",email); username=username = username=parts[0]; // Display the username echo $username."\n"; ?>

`