Home » Php » php – How to get the base URL of an external website

php – How to get the base URL of an external website

Posted by: admin July 12, 2020 Leave a comment

Questions:

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!

How to&Answers:


$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 )

Answer:

use parse_url

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

Answer:

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