How to get userid and mail server from email using PHP string functions

PHP string functions explode() and strstr() are very useful functions when working on strings. While explode() converts a string into array using a separator, strstr() searches for a string in another string.


Using explode() function you can create an array of values separated by a specific character from a string. if the string is "", using '@' as the separator we can create an array as below:

Here, $arr is an array of two elements, first element is "test_email" (userid) and second element is "" (server name). So, using this function you can easily get the email userid and the mail server name form an email id.


We can do the same thing using strstr() or stristr() (case-insensitive) function. Using strstr() you can search a particular character/string in another string and get the values before or after that particular searched character/string. See below:

We will write two simple programs to display user id and mail server name from an email id.

Using explode() function


Using '@' as the separator, an array is created with 2 elements. I named this file as explode.php and saved it in a folder named "php" under htdocs.

Using strstr() function


Here, we are using '@' as the search character. When we use 'true' as third parameter, it returns the string before the first occurrence of '@'. So we get the userid. If I omit the third parameter, then it gives the string from the first occurrence of '@'. Then we used substr() function to get rid of '@'. So this gives the server name. Let us name this file as strstr.php and save it in a folder "php" under htdocs.

explode and strstr functions in phpTest the Application

Make sure your in your XAMPP control panel Apache is running. Open the browser and run localhost/php/explode.php. You will see below screen;

explode and strstr functions in php

Similarly, if you run localhost/php/strstr.php, you will see below output:

explode and strstr functions in php

You can see both the outputs are same.

explode and strstr functions in phpConclusion

This was an example of using string functions in PHP. There are many useful string functions available in PHP, you can use them while working in PHP.