【问题标题】:Split PHP String of a URL拆分 URL 的 PHP 字符串
【发布时间】:2015-05-29 11:01:06
【问题描述】:

我怎样才能只返回一个域名的TLD

例如,如果我有以下情况:

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

domain.co.uk 也一样

对于所有其他 TLDs (.com, .co, .org etc) 也是如此

有没有不使用Regex的简单方法在PHP中做到这一点

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

【问题讨论】:

  • 这无济于事。 @MangeshSatheIND
  • parse_url 会给你域名然后对其执行正则表达式,你可以得到预期的 .com /.co.uk 等。
  • OP已经有域名

标签: php regex string url explode


【解决方案1】:

您可以使用名为 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 tlds。

【讨论】:

  • 虽然这个答案(在后台)正在使用正则表达式,但提供的资源 (publicsuffix.org) 非常有用! +1
【解决方案2】:
$returnHostName = parse_url($url, PHP_URL_HOST) //it will retrun 'domain' in your case
$returnArrayType = explode($returnHostName, $returnHostName); //explode it from string 'domain'

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

检查它是否会工作。

【讨论】:

    【解决方案3】:

    不是正则表达式,不是 parse_url() 对你没有帮助。

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

    【讨论】:

      【解决方案4】:

      此功能适用于 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];
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多