Extracting the domain of an email with PHP

Published on 2022-01-27 • Modified on 2022-01-27

In this snippet, we see how to extract the domain of an email with PHP. First, a solution with plain PHP, then with the Symfony string component: it's much more elegant and readable, isn't it? I like the String component 😊! Check out other solutions by clicking on the links below.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use function Symfony\Component\String\u;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet187Trait
{
    public function snippet187(): void
    {
        $email = 'email@example.com';

        // With PHP
        $domain = substr($email, (int) strpos($email, '@') + 1);
        echo 'PHP: '.$domain.PHP_EOL;

        // with the Symfony string component
        $domain2 = u($email)->after('@');
        echo 'Symfony String component: '.$domain2;

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  More on the web

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

use function Symfony\Component\String\u;

/**
 * @see Snippet187Trait
 */
final class Snippet187Test extends KernelTestCase
{
    /**
     * @see Snippet187Trait::snippet187
     */
    public function testSnippet187(): void
    {
        $email = 'email@example.com';
        $domain = substr($email, (int) strpos($email, '@') + 1);
        $domain2 = u($email)->after('@');

        self::assertSame($domain, 'example.com');
        self::assertSame($domain, (string) $domain2);
    }
}