拆分URL的PHP​​字符串

时间:2015-05-29 11:01:06

标签: php regex string url explode

如何只返回域名TLD

例如,如果我有以下内容:

www.domain.co.uk我想仅返回.co.uk

domain.co.uk

相同

和所有其他TLDs (.com, .co, .org etc)

相同

有没有使用Regex

在PHP中执行此操作的简单方法

我在考虑使用explode,但我不太熟悉

4 个答案:

答案 0 :(得分:2)

您可以使用名为tldextract.php的库。

在此处查找https://github.com/data-ac-uk/equipment/blob/master/_misc/tldextract.php

用法非常简单:

$extract = new TLDExtract();
$components = $extract('http://forums.bbc.co.uk/');
echo $components['tld']; // co.uk

现在有多简单?

如果您阅读了代码,则可以看到它在fetchTldList()函数中使用了大量list个tld。

答案 1 :(得分:1)

$returnHostName = parse_url($url, PHP_URL_HOST) //it will retrun 'domain' in your case
$returnArrayType = explode($returnHostName, $returnHostName); //explode it from string 'domain'

现在,变量 returnArrayType 包含您想要的输出,但是以数组的形式,您可以通过调用它的索引来获取它。

检查它是否有效。

答案 2 :(得分:1)

不是正则表达式,而不是parse_url()对你没用。

您需要使用Public Suffix List扩展TLD的库,我建议您使用TLDExtract

答案 3 :(得分:0)

此功能适用于www而非www域名。不适用于子域名。为了获得更好的结果,您需要使用正则表达式或库。

    $domain = "www.domain.co.uk";
    function tld($domain)
    {
        if (strstr('www', $domain)) {
            $part = 3;
        } else {
            $part = 2;
        }
        $expld = explode('.', $domain);
        if (count($expld) > $part) {
            return $expld[count($expld) - 2] . '.' . $expld[count($expld) - 1];
        } else {
            return $expld[count($expld) - 1];
        }
    }