Paul Dessert
Paul Dessert

Reputation: 6389

How to get the base URL of an external website

I'm using cURL to return data from external sites. How can I return the base URL of a site with PHP?

For example, I have this URL: http://www.bestbuy.com/site/Insignia%26%23153%3B+-+55%22+Class+/+1080p+/+120Hz+/+LCD+HDTV/2009148.p?id=1218317000232&skuId=2009148

I just want http://www.bestbuy.com

Thanks!

Upvotes: 7

Views: 5378

Answers (3)

kingpin
kingpin

Reputation: 1498

REGEX :)

use this one (not sure if it will work on php but you can modify it slightly if needed)

/^((?:http:\/\/|https:\/\/)?(?:.+?))(?:\s*$|\/.*$)/

so this will optionally match http:// or https:// (? sign after \/\/) ) then will lazy match until either end of line or / if exists

and your desired url is in the first capture group

optionally you can omit ?: everywhere in the regex and you can get

  • first: full url
  • second: params
  • third: protocol
  • fourth: domain

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205


$url = "http://www.bestbuy.com/site/Insignia%26%23153%3B+-+55%22+Class+/+1080p+/+120Hz+/+LCD+HDTV/2009148.p?id=1218317000232&skuId=2009148";
echo "";
print_r(parse_url($url));

//Would give you Array ( [scheme] => http [host] => www.bestbuy.com [path] => /site/Insignia%26%23153%3B+-+55%22+Class+/+1080p+/+120Hz+/+LCD+HDTV/2009148.p [query] => id=1218317000232&skuId=2009148 )

Upvotes: 16

j_mcnally
j_mcnally

Reputation: 6968

use parse_url

http://php.net/manual/en/function.parse-url.php

Upvotes: 2

Related Questions