Regular Expression to Extract Domain Only From a URL

I want a single Regular expression that can extract domain from the URL. The URL can be in the following formats:

http://domain.com
https://domain.com/blah/blah...
http://www.domain.com/.....
www.domain.com
domain.com
../../bank_links1/%20http:/www.o2bancorp.com
http:/domain.com (a single / can occur by mistake)
http:/www.domain.com (a single / can occur by mistake)

From all of the above i want to extract only the domain name...
LVL 2
waqarkhan88Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Terry WoodsIT GuruCommented:
It's easy to match domain.com but it becomes much tougher if you want to include every possible top level domain eg .org .nz .de etc

Do you need top level domains other than .com?
0
Terry WoodsIT GuruCommented:
Anyway, try this:

preg_match("@(?:https?//?[a-z\d][a-z\d\-]*[a-z\d])(\.[a-z\d][a-z\d\-]*[a-z\d]){1,}@i",$url);
0
käµfm³d 👽Commented:
@TerryAtOpus

You forgot the colon after the protocol  :)

I believe the following passed all of your above examples:
preg_match("#(?:(?:https?|s?ftp|mailto|gopher)://?)?(?:[a-z0-9-]+\.){0,}([a-z0-9-]+){1,}\.#i",$url);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

waqarkhan88Author Commented:
actually i just want to match domain like if i have a url : http://www.yahoo.com then i only want to get "yahoo"...
0
waqarkhan88Author Commented:
perfect :)
0
käµfm³d 👽Commented:
NP. Glad to help  :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Regular Expressions

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.