Mark
Mark

Reputation: 5653

php - regex hostname extraction

I have been looking around for a regex expression that will spit out just the 'stackoverflow' part and no www. or .com etc. All I could find was to check if the url's were valid... I have used php's url filter to determine that much I now am looking to determine which site it is.

I have never written an expression before so I am hoping someone can check it/recommend a better solution.

preg_match('@^(?:http://)(?:www.)?([^.]+)@i', $url, $matches)

edit: All the url's I am dealing with are .com if that helps

Upvotes: 0

Views: 2911

Answers (4)

Galen
Galen

Reputation: 30170

one-liner without using regular expressions!!!

$url = 'http://stackoverflow.com';
$d = array_shift( explode( '.', str_replace('www.', '', parse_url( $url, PHP_URL_HOST )) ) );
echo $d;

Upvotes: 2

Waleed Amjad
Waleed Amjad

Reputation: 6808

Have you considered PHP's parse_url() function?

Upvotes: 5

Matteo Riva
Matteo Riva

Reputation: 25060

preg_match('#https?://(?:www.)?(.*?)\.com#i', $str, $match);

Upvotes: 0

johannes
johannes

Reputation: 15989

If you know that the thing you're having is a URL and the domain end in .com a simple thing like

preg_match('#([^\.]*)\.com#', $url, $matches);

should do the trick.

While this will fail on a domain like www.com.foo.com but might be enough, depending on your situation.

Upvotes: 0

Related Questions