Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get the domain from an email address or a link

Short answer

For a link use parse_url():

<?php
 
echo parse_url('https://shop.example.com/catalog?page=2', PHP_URL_HOST);

Output:

shop.example.com

The domain from an email address

Take everything after the last @ sign:

<?php
 
$email = 'anna@mail.example.com';
 
echo substr($email, strrpos($email, '@') + 1);

Output:

mail.example.com

Without www

The prefix is removed separately:

<?php
 
$host = parse_url('https://www.example.com/about', PHP_URL_HOST);
 
echo preg_replace('/^www\./', '', $host);

Output:

example.com

Functions used in this recipe

  • parse_url — Splits a URL into its parts.
  • strstr — Returns the part of a string starting at the first occurrence of a substring.
  • explode — Splits a string into an array by a separator.

Thanks for reading!

Donate to the site — we work hard for you.