首頁 > 後端開發 > php教程 > 如何在 PHP 中從不同格式的 URL 中提取基本網域?

如何在 PHP 中從不同格式的 URL 中提取基本網域?

Linda Hamilton
發布: 2024-10-17 17:12:02
原創
823 人瀏覽過

How to Extract the Base Domain from URLs with Varying Formats in PHP?

How to Extract the Primary Domain Name from a Variety of URL Formats in PHP

Introduction:

When working with URLs, it is often necessary to extract the primary domain name, excluding any subdomains. This can be a challenging task due to the wide range of URL formats that exist.

Solution:

Fortunately, there is a relatively straightforward solution using a combination of PHP functions. By utilizing parse_url and some string manipulation techniques, we can effectively extract the primary domain name from any URL format.

Step 1: Parse the URL

Using parse_url, we can extract the host part of the URL, which includes both the primary domain and any subdomains.

<code class="php">$info = parse_url($url);
$host = $info['host'];</code>
登入後複製

Step 2: Separate the Host Name and TLD

We then split the host string into an array based on periods using the explode function. The second to last string in the array represents the hostname, while the last string represents the top-level domain (TLD).

<code class="php">$host_names = explode(".", $host);
$bottom_host_name = $host_names[count($host_names)-2] . "." . $host_names[count($host_names)-1];</code>
登入後複製

Step 3: Combine the Hostname and TLD

By concatenating the hostname and TLD strings, we obtain the primary domain name.

<code class="php">echo $bottom_host_name;</code>
登入後複製

Explanation:

  • parse_url effectively extracts the host portion of the URL, including subdomains.
  • explode breaks the host into an array based on periods, allowing isolation of hostname and TLD.
  • count determines the number of elements in the array to identify the second-to-last string (hostname) and last string (TLD).
  • Concatenation combines the hostname and TLD into the primary domain name.

以上是如何在 PHP 中從不同格式的 URL 中提取基本網域?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板