user4756836
user4756836

Reputation: 1337

Regex to match domain failing on input

I created a regex to match the domain name out of the input:

$pattern = '/\w+\..{2,3}(?:\..{2,3})?(?:$|(?=\/))/i';
$url = 'http://wwe.com';
if (preg_match($pattern, $url, $matches) === 1) {
    echo $matches[0];
}

It works fine for this input:

http://google.com // output:google.com

But I am not able to achieve it for these inputs: (if the user enters an extra www

http://www.google.com // output:google.com
http://www.www.google.com // output:google.com

What am I missing?

Any help on this will be appreciated

Upvotes: 0

Views: 42

Answers (1)

drew010
drew010

Reputation: 69977

What about this?

<?php

$urls = [
    'http://google.com',
    'http://www.google.com',
    'http://www.www.google.com',
];

foreach($urls as $url) {
    $url = parse_url($url, PHP_URL_HOST);
    $url = preg_replace('/^(www\.)+/', '', $url);
    echo $url . "\n";
}

Output:

google.com
google.com
www.google.com

Upvotes: 1

Related Questions