Bagaimana untuk mengekstrak nama domain dari URL dalam PHP menggunakan kaedah yang berbeza?

DDD
Lepaskan: 2024-10-17 17:17:02
asal
1021 orang telah melayarinya

How to Extract the Domain Name from a URL in PHP Using Different Methods?

Extracting the Domain Name from Any URL Using PHP

In PHP, you encounter various scenarios where you need to retrieve the domain name from a given URL. To cater to this requirement, here's a comprehensive solution that handles URLs in different formats.

Regular Expression Method

The following regular expression can be used to extract the domain name from any URL:

<code class="php">$regex = '/^(http|https):\/\/[a-z0-9]*\.[a-z0-9.]+/i';</code>
Salin selepas log masuk

This regular expression will match all URLs, including subdomains, and capture the domain name.

Parse URL Method

Alternatively, you can use the parse_url() function to extract the host from the URL. The host contains the domain name and any subdomains.

<code class="php">$info = parse_url($url);
$host = $info['host'];</code>
Salin selepas log masuk

Separating the Domain and TLD

To extract only the domain name (without any subdomains) and the top-level domain (TLD), you can use the following code:

<code class="php">$host_names = explode(".", $host);
$bottom_host_name = $host_names[count($host_names)-2] . "." . $host_names[count($host_names)-1];</code>
Salin selepas log masuk

This code splits the host into its component parts and extracts the domain name and TLD.

Example Usage

To demonstrate the usage of these methods, consider the following code:

<code class="php">$url = 'https://www.example.com/foo/bar';

// Using regular expression
preg_match($regex, $url, $matches);
$domain_name = $matches[0];

// Using parse_url and explode
$info = parse_url($url);
$host = $info['host'];
$host_names = explode(".", $host);
$bottom_host_name = $host_names[count($host_names)-2] . "." . $host_names[count($host_names)-1];

echo "Domain name (regex): " . $domain_name . "<br>";
echo "Domain name and TLD (parse_url): " . $bottom_host_name;</code>
Salin selepas log masuk

This code will output:

Domain name (regex): example.com
Domain name and TLD (parse_url): example.com
Salin selepas log masuk

Atas ialah kandungan terperinci Bagaimana untuk mengekstrak nama domain dari URL dalam PHP menggunakan kaedah yang berbeza?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan