Home >Backend Development >PHP Tutorial >How to Extract the Domain from a URL Using PHP's parse_url()?
Domain Parsing
Extracting the domain from a URL is a common task in web development. This post explores a method for accomplishing this using the parse_url() function.
parse_url()
PHP's parse_url() function allows you to parse a URL into its individual components. It returns an array containing information such as the scheme, host, port, path, query string, and fragment.
To extract the domain from a URL using parse_url(), you need the host component. Here's an example:
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'; $parse = parse_url($url); echo $parse['host']; // prints 'google.com'
The resulting host component will be the domain of the URL, including the subdomain if there is one. This behavior holds true for both the www and non-www versions of a domain.
$url = 'http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html'; $parse = parse_url($url); echo $parse['host']; // prints 'www.google.com' $url = 'http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html'; $parse = parse_url($url); echo $parse['host']; // prints 'google.co.uk'
Note: parse_url() assumes the URL is well-formed. It may not handle malformed URLs gracefully.
The above is the detailed content of How to Extract the Domain from a URL Using PHP's parse_url()?. For more information, please follow other related articles on the PHP Chinese website!