2

Need a regular expression (using PHP) to match a domain name. Examples:

http://sub.domain.com/somefolder/index.html -> domain.com
somedomain.info -> somedomain.info
http://anotherdomain.org/home -> anotherdomain.org
www.subdomain.anothersubdomain.maindomain.com/something/ -> maindomain.com
Alex K.
  • 171,639
  • 30
  • 264
  • 288
Caballero
  • 11,546
  • 22
  • 103
  • 163
  • 1
    http://stackoverflow.com/questions/1236173/regexp-for-validating-au-domain-names and http://stackoverflow.com/questions/4963202/domain-regex-split – mario May 20 '11 at 12:35

3 Answers3

2

This might not be a job for regexes, but for existing tools in your language of choice. Regexes are not a magic wand you wave at every problem that happens to involve strings. You probably want to use existing code that has already been written, tested, and debugged.

In PHP, use the parse_url function.

Perl: URI module.

Ruby: URI module.

.NET: 'Uri' class

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
0

You can use this one as well:

((?>[a-z\-0-9]{2,}\.){1,}[a-z]{2,8})(?:\s|/)

It will match all the domain names found in a given text, while returning the domain found in the first group.

Nikola Petkanski
  • 4,724
  • 1
  • 33
  • 41
-1

This parses Complete Urls you can check, match objects 2nd element for domain name

(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

Works for me :)

Rajeev
  • 4,571
  • 2
  • 22
  • 35