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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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?
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);
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

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
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

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"...
waqarkhan88Author Commented:
perfect :)
käµfm³d 👽Commented:
NP. Glad to help  :)
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.