在php中获取域名(不是子域) [英] Get domain name (not subdomain) in php

查看:101
本文介绍了在php中获取域名(不是子域)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个URL,可以是以下任何一种格式:

I have a URL which can be any of the following formats:

http://example.com
https://example.com
http://example.com/foo
http://example.com/foo/bar
www.example.com
example.com
foo.example.com
www.foo.example.com
foo.bar.example.com
http://foo.bar.example.com/foo/bar
example.net/foo/bar

本质上,我需要能够匹配任何常规URL.如何通过单个正则表达式从所有这些文件中提取example.com(或.net,无论tld碰巧是什么.我需要将此文件与任何TLD一起使用)?

Essentially, I need to be able to match any normal URL. How can I extract example.com (or .net, whatever the tld happens to be. I need this to work with any TLD.) from all of these via a single regex?

推荐答案

那么您可以使用parse_url来获取主机:

Well you can use parse_url to get the host:

$info = parse_url($url);
$host = $info['host'];

然后,您可以做一些有趣的事情,仅获取TLD和主机

Then, you can do some fancy stuff to get only the TLD and the Host

$host_names = explode(".", $host);
$bottom_host_name = $host_names[count($host_names)-2] . "." . $host_names[count($host_names)-1];

不太优雅,但应该可以使用.

Not very elegant, but should work.

如果您想要一个解释,它就在这里:

If you want an explanation, here it goes:

首先,我们使用parse_url的功能来解析方案之间的所有内容(http://等),...解析URL. :)

First we grab everything between the scheme (http://, etc), by using parse_url's capabilities to... well.... parse URL's. :)

然后我们获取主机名,并根据句点所在的位置将其分成一个数组,因此test.world.hello.myname将变为:

Then we take the host name, and separate it into an array based on where the periods fall, so test.world.hello.myname would become:

array("test", "world", "hello", "myname");

然后,我们获取数组(4)中的元素数量.

After that, we take the number of elements in the array (4).

然后,我们从中减去2得到倒数第二个字符串(在您的示例中为主机名或example)

Then, we subtract 2 from it to get the second to last string (the hostname, or example, in your example)

然后,我们从中减去1以获得最后一个字符串(因为数组键从0开始),也称为TLD

Then, we subtract 1 from it to get the last string (because array keys start at 0), also known as the TLD

然后,我们将这两部分与一个句点结合起来,您便有了基本的主机名.

Then we combine those two parts with a period, and you have your base host name.

这篇关于在php中获取域名(不是子域)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆