Home > Backend Development > PHP Tutorial > How to Extract the Domain from a URL Using PHP's parse_url()?

How to Extract the Domain from a URL Using PHP's parse_url()?

Linda Hamilton
Release: 2024-12-16 17:18:22
Original
508 people have browsed it

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'
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template