w3resource

PHP String Exercises: Extract the user name from the specified email ID


6. Extract Username from Email

Write a PHP script to extract the user name from the following email ID.

Sample String : '[email protected]'

Visual Presentation:

PHP String Exercises: Extract the user name from the specified email ID

Sample Solution:

PHP Code:

<?php
$mailid  = '[email protected]';     // Assigns an email address to the variable $mailid
$user = strstr($mailid, '@', true); // Finds the first occurrence of '@' in $mailid and returns the substring before it
echo $user."\n";                    // Outputs the substring before the '@' character in the email address
?>

Output:

rayy

Explanation:

The above PHP code extracts the username from a given email address stored in the variable '$mailid'. It uses the "strstr(") function with the third parameter set to 'true' to return the substring before the first occurrence of the '@' character. Finally, it echoes the extracted username.

Flowchart:

Flowchart: Extract the user name from the specified email ID

For more Practice: Solve these Related Problems:

  • Write a PHP function to split an email address at the "@" symbol and return the username part.
  • Write a PHP script to extract and validate the username from an email, ensuring it contains only alphanumeric characters.
  • Write a PHP program to process an array of email addresses and output the username for each, using string functions.
  • Write a PHP script to handle multiple email formats and extract the substring before the "@" sign, even if the email contains subdomains.

Go to:


PREV : Extract Filename from Path.
NEXT : Get Last Three Characters.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.