w3resource

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

PHP String: Exercise-6 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to extract the file name from the specified string.
Next: Write a PHP script to get the last three characters of a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-string-exercise-6.php