Passed
Push — master ( bd8ef3...a68137 )
by ma
02:03
created

UrlTool::getMainDomain()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
nc 4
nop 1
dl 0
loc 22
rs 9.9
c 1
b 0
f 0
1
<?php
2
namespace tinymeng\tools;
3
/**
4
 * Url
5
 */
6
class UrlTool{
7
8
    /**
9
     * 获取url中主域名
10
     * @param $url
11
     * @return array|int|string
12
     */
13
    static function getMainDomain($url) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
14
        $host = parse_url($url, PHP_URL_HOST); // 获取host部分
15
        if (!$host) {
16
            return '';
17
        }
18
19
        // 假设主域名至少有两个部分(例如:example.com),并且不包含子域名
20
        $parts = explode('.', $host);
21
        $count = count($parts);
22
23
        /*
24
         *  通常情况下,主域名由最后两个部分组成
25
         *  但这可能不适用于所有情况,特别是当TLD是.co.uk这样的
26
         */
27
        if ($count > 2) {
28
            return implode('.', array_slice($parts, -2)); // 返回最后两个部分的组合
29
        } elseif ($count == 2) {
30
            // 如果只有两个部分,则直接返回整个host作为主域名
31
            return $host;
32
        } else {
33
            // 如果少于两个部分,可能不是一个有效的域名
34
            return '';
35
        }
36
    }
37
}
38