How to get the base URL of an external website

I use 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!

+6
source share
3 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 )

+13
source

REGEX :)

use this one (not sure if it will work on php, but you can change it a bit if necessary)

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

therefore it will not necessarily match http: // or https: // (? sign after \/\/) ), then there will be a lazy match to the end of the line or / if exists

and your desired url is in the first capture group

maybe you can omit ?: everywhere in regex and you can get

  • first: full URL
  • second: params
  • third: protocol
  • fourth: domain
0
source

Source: https://habr.com/ru/post/909257/


All Articles