Wednesday, November 19, 2025
HomeLanguagesHow to extract the user name from the email ID using PHP...

How to extract the user name from the email ID using PHP ?

Given a string email address, extract the username.

Input: ‘priyank@neveropen.com’
Output: priyank

Input: ‘princepriyank@gfg.com’
Output: 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.

  • Step 1: Define a variable and store the value of the email address in it.

    $email= 'priyank@neveropen.com';
  • Step 2: Get the username by slicing the string till the first occurrence of ‘@’ using this line

    $username=strstr($email,'@',true);
  • Step 3: Display the username using an echo statement.

    echo $username."\n";

Example:

PHP




<?php
  // Define Email Address
  $email  = 'priyank@neveropen.com';
  
  // Get the username by slicing string
  $username = strstr($email, '@', true);
  
  // Display the username
  echo $username."\n";
?>


Output

priyank

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 “@”.

  • Step 1: Define a variable email and store the value of email address in it.

    $email= 'princepriyank@neveropen.com';
  • Step 2: Get the username by exploding (dividing) the string using ‘@’ as a separator and store the first part in the variable username.

    $parts = explode("@",$email);
    $username = $parts[0];
  • Step 3: Display the username using this code.

    echo $username."\n";

Example:

PHP




<?php
// Define Email Address
$email  = 'princepriyank@neveropen.com';
  
// Get the username by dividing mailid using'@' as separator
$parts = explode("@",$email);
$username = $parts[0];
  
// Display the username
echo $username."\n";
?>


Output

princepriyank
RELATED ARTICLES

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6775 POSTS0 COMMENTS
Nicole Veronica
11924 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6903 POSTS0 COMMENTS
Ted Musemwa
7159 POSTS0 COMMENTS
Thapelo Manthata
6859 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS