Home » Php » php – preg_replace and regexp to get the domain

php – preg_replace and regexp to get the domain

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a code which return the clean domain from HTTP_HOST

preg_replace('#^(.*\.)?(.*\..*)$#', '$2', $_SERVER['HTTP_HOST'])

But in case the domain is like somedomain.co.uk – it returns the co.uk only.
Can you pls help me to remake the RegExp to return the correct domain in this case?
Thanks a lot!

How to&Answers:

You should try this:

preg_replace('#^(https?:\/\/)?(www\d?\.)?([^\/\?]+)(.*)#', '$3', $url)

It works for the following cases:

<?php 

$urls = [
    'https://www.somedomain.co.uk', 
    'http://www.somedomain.co.uk', 
    'www.somedomain.co.uk/something', 
    'www.somedomain.co.uk?q=1',
    'www2.somedomain.co.uk/something',
    'somedomain.co.uk',
    '192.168.1.1/something?q=1&x=2',
];

foreach($urls as $url) {
    echo preg_replace('#^(https?:\/\/)?(www\d?\.)?([^\/\?]+)(.*)#', '$3', $url) . '<br>';
}