Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zarcoder's avatar

Vanilla PHP

I'm a paying Laracasts subscriber but I'm not sure whether I'm allowed to ask vanilla php questions here? Since Jeff did do a PHP Practitioner I'll ask away...

I have a text file with various names, tags, delimiters and emails in it. I want to extract the domain part of all the emails in this text file which I achieved to do (So [email protected] now output example.com). Now I need to get unique results and sort the domain names alphabetically. If you look at the code below I can't use array_unique() as the output is not an array, but a string. Do I need to explode() the data? If so, how do I echo the strings? I don't want the var_dump or print_r output. An example would help very much.

Here is the code I've written thus far.

<?php

$string = file_get_contents('text.txt');
$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
$result = preg_match_all($pattern, $string, $matches);
if($result) {
    foreach(array_unique($matches[0]) as $email) {
        $domain = strstr($email, '@', false);
        $domain1 = str_replace('@', '', $domain);
        echo $domain1 . '<br />';
    } 
}
0 likes
4 replies
36864's avatar
36864
Best Answer
Level 13

Looks like all you really need to do there is store the domains you find in an array, and then sort it.

<?php

$string = file_get_contents('text.txt');
$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
$result = preg_match_all($pattern, $string, $matches);
$domains = [];
if($result) {
    foreach(array_unique($matches[0]) as $email) {
    $domain = strstr($email, '@', false);
    $domain1 = str_replace('@', '', $domain);
//  echo $domain1 . '<br />';
    $domains[$domain1] = $domain1;
} 
asort($domains);
foreach($domains as $domain) {
    echo $domain . '<br />';
}
}

Alternatively, you could probably change that regex to match only the domain parts of the email addresses and skip a step.

2 likes
zarcoder's avatar

Thank you. Seems like I get a syntax error?

Parse error: syntax error, unexpected 'foreach' (T_FOREACH) in C:\xampp\htdocs\test\domain.php on line 14

36864's avatar

I missed a semicolon. Updated my previous post.

zarcoder's avatar

I guess I should have picked that up myself. Thank you kindly

Please or to participate in this conversation.