在PHP中获取没有www和.com的域名

时间:2014-11-07 07:38:27

标签: php regex subdomain

我需要从网址中获取域名,不包括" www"和" .com"或" .co.uk"或其他任何东西。

实施例 -

我有以下网址 -

http://www.example.com
http://www.example.co.uk
http://subdomain.example.com
http://subdomain.example.co.uk

" .com" ," .org" ," .co.in"," .co.uk"。

3 个答案:

答案 0 :(得分:2)

(?:https?:\/\/)?(?:www\.)?(.*)\.(?=[\w.]{3,4})

试试这个。看看demo.Grab捕获。

http://regex101.com/r/bW3aR1/2

答案 1 :(得分:1)

您应该将PHP函数parse_url()str_replace()或正则表达式结合使用,甚至可能爆炸。这取决于一些事情:

注意事项:

  • 是否总会有子域?
  • 是否有允许的子域名的具体列表?

我会做这样的事情:

<?php
$url = 'http://www.something.com';
$parts = explode('.', parse_url($url, PHP_URL_HOST));
echo $parts[1]; // "something"

答案 2 :(得分:1)

我试着这对我有用。

    $original_url="http://subdomain.example.co.uk"; //try with all urls above

    $pieces = parse_url($original_url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain,    $regs)) {
       echo strstr( $regs['domain'], '.', true );
    }

Output- example

我从这里得到这个 Get domain name from full URL