获取一个域名的主域名
class DomainService { protected $cacheKey = 'domain-cache'; protected $domainList; public function getDomainSuffix() { if (!$this->domainList) { $cacheList = \Yii::$app->cacheFile->get($this->cacheKey); if ($cacheList) { $this->domainList = $cacheList; } else { $this->domainList = $this->syncRemoteDomain(); \Yii::$app->cacheFile->set($this->cacheKey, $this->domainList); } } return $this->domainList; } public function syncRemoteDomain() { $res = CurlService::getIns()->get('https://publicsuffix.org/list/effective_tld_names.dat'); if ($res->getErrorMsg()) { return []; } $body = $res->getBody(); $domainSuffixList = explode("\n", $body); $domainSuffixList = array_filter($domainSuffixList, function ($row) { $row = trim($row); if (!empty($row) && substr($row, 0, 2) != '//') { return true; } return false; }); return $domainSuffixList; } public function getMain(string $domain) { $domainList = $this->getDomainSuffix(); $domainMap = array_flip($domainList); $origin = $domainSep = explode('.', $domain); $len = count($domainSep); for ($i = 0; $i < $len; $i++) { unset($domainSep[$i]); if (count($domainSep) == 0) { break; } $s = implode('.', $domainSep); if (isset($domainMap[$s])) { return '*.'.$origin[$i].'.'.$s; } } return $domain; } }