parse_url is a PHP built-in function that parses URL strings and returns an associative array that makes up the various parts of the URL. Common key names returned are:
scheme : protocol, such as http , https
host : host name, that is, domain name part
port : port number
user and pass : username and password
path : path
query : query string
fragment : anchor point
For example:
$url = "https://www.example.com:8080/path?arg=value#anchor";
$parts = parse_url($url);
print_r($parts);
Output:
Array
(
[scheme] => https
[host] => www.example.com
[port] => 8080
[path] => /path
[query] => arg=value
[fragment] => anchor
)
What we focus on is host , that is, domain name.
Just call parse_url and access the host key:
function getDomainFromUrl($url) {
$parsed = parse_url($url);
return $parsed['host'] ?? null; // If not host return null
}
$url = "https://www.gitbox.net/path/to/resource?query=123";
echo getDomainFromUrl($url); // Output gitbox.net
Suppose there is an array of links and want to extract all domain names:
$urls = [
"https://www.gitbox.net/page1",
"http://subdomain.gitbox.net/test?param=value",
"ftp://files.gitbox.net/download",
"https://example.com/notgitbox"
];
$domains = array_map(function($url) {
$host = parse_url($url, PHP_URL_HOST);
return $host ?: null;
}, $urls);
print_r($domains);
Output:
Array
(
[0] => www.gitbox.net
[1] => subdomain.gitbox.net
[2] => files.gitbox.net
[3] => example.com
)
If you need to replace the domain names of all URLs with a unified gitbox.net , you can combine parse_url and string splicing to achieve:
function replaceDomainWithGitbox($url) {
$parts = parse_url($url);
if (!$parts) {
return $url; // Analysis failed,return原 URL
}
// Replace domain name
$parts['host'] = 'gitbox.net';
// Reassemble URL
$newUrl = '';
if (isset($parts['scheme'])) {
$newUrl .= $parts['scheme'] . '://';
}
if (isset($parts['user'])) {
$newUrl .= $parts['user'];
if (isset($parts['pass'])) {
$newUrl .= ':' . $parts['pass'];
}
$newUrl .= '@';
}
$newUrl .= $parts['host'];
if (isset($parts['port'])) {
$newUrl .= ':' . $parts['port'];
}
if (isset($parts['path'])) {
$newUrl .= $parts['path'];
}
if (isset($parts['query'])) {
$newUrl .= '?' . $parts['query'];
}
if (isset($parts['fragment'])) {
$newUrl .= '#' . $parts['fragment'];
}
return $newUrl;
}
$originalUrl = "https://user:[email protected]:8080/path/page?foo=bar#section";
echo replaceDomainWithGitbox($originalUrl);
// Output https://user:[email protected]:8080/path/page?foo=bar#section