Home > Backend Development > PHP Tutorial > How to Extract Domain Names from URLs in PHP?

How to Extract Domain Names from URLs in PHP?

Barbara Streisand
Release: 2024-10-17 17:12:30
Original
1138 people have browsed it

How to Extract Domain Names from URLs in PHP?

Extracting Domain Names from URLs in PHP

Extracting the domain name (not subdomain) from a URL can be a task that requires careful consideration of various URL formats. To address this challenge, PHP provides the parse_url() function, which enables the extraction of various URL components, including the host.

To obtain the domain name, follow these steps:

  1. Parse the URL: Using parse_url($url), extract the $host from the URL.
  2. Separate Host Name: Split the host into an array ($host_names) based on periods.
  3. Get Bottom Host Name: Subtract 2 from the array count to get the second to last string, representing the host name (e.g., "example").
  4. Get TLD: Subtract 1 from the array count to get the last string, representing the TLD (e.g., "com").
  5. Combine Host and TLD: Concatenate the host name and TLD with a period (e.g., "example.com").

This method may not be the most elegant, but it efficiently extracts the domain name from complex URL formats, including those with subdomains, TLDs, and additional path components.

The above is the detailed content of How to Extract Domain Names from URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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