Extraction du domaine d'une email avec PHP

Publié le 27/01/2022 • Actualisé le 27/01/2022


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons comment extraire le domaine d'une email avec PHP. Tout d'abord, une solution avec PHP uniquement, puis en utilisant le composant String de Symfony : beaucoup plus élégant et lisible, non ? J'aime beaucoup le composant String 😊 ! Jetez un coup d'œil aux autres solutions possibles en cliquant sur les liens ci-dessous.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use function Symfony\Component\String\u;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
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! 😁
    }
}

 Exécuter le snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow   Lire la doc  Plus sur le web

  Travaillez avec moi !

<?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);
    }
}