Php 如果找到子域,则从url字符串中删除子域

Php 如果找到子域,则从url字符串中删除子域,php,url-rewriting,Php,Url Rewriting,我有一系列域,如下所示: domain.com second.com www.third.com www.fourth.fifth.com sixth.com seventh.eigth.com 我想要的是一个只返回主机的函数。没有子域 到目前为止,我已经有了以下代码来获取主机名: $parse = parse_url($url); $domain = $parse['host']; 但这只会返回以下结果: domain.com second.com third.com fourth.fif

我有一系列域,如下所示:

domain.com
second.com
www.third.com
www.fourth.fifth.com
sixth.com
seventh.eigth.com
我想要的是一个只返回主机的函数。没有子域

到目前为止,我已经有了以下代码来获取主机名:

$parse = parse_url($url);
$domain = $parse['host'];
但这只会返回以下结果:

domain.com
second.com
third.com
fourth.fifth.com
sixth.com
seventh.eigth.com
不过,我需要这个输出:

domain.com
second.com
third.com
fifth.com
sixth.com
eigth.com
尝试使用str_replace()

试试这个代码

 <?php
    /**
    * @param string $domain Pass $_SERVER['SERVER_NAME'] here
    * @param bool $debug
    *
    * @debug bool $debug
    * @return string
    */
    function get_domain($domain, $debug = false) {
        $original = $domain = strtolower($domain);     
        if (filter_var($domain, FILTER_VALIDATE_IP)) { return $domain; }    

        $debug ? print('<strong style="color:green">&raquo;</strong> Parsing: '.$original) : false; //DEBUG 

        $arr = array_slice(array_filter(explode('.', $domain, 4), function($value){
                            return $value !== 'www'; }), 0); //rebuild array indexes

        if (count($arr) > 2)    {
            $count = count($arr);
            $_sub = explode('.', $count === 4 ? $arr[3] : $arr[2]);

            $debug ? print(" (parts count: {$count})") : false; //DEBUG

            if (count($_sub) === 2)  { // two level TLD
                $removed = array_shift($arr);
                if ($count === 4) // got a subdomain acting as a domain
                    $removed = array_shift($arr);            
                $debug ? print("<br>\n" . '[*] Two level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false; //DEBUG
            }
            elseif (count($_sub) === 1){ // one level TLD
                $removed = array_shift($arr); //remove the subdomain             
                if (strlen($_sub[0]) === 2 && $count === 3) // TLD domain must be 2 letters
                    array_unshift($arr, $removed);                
                else{
                    // non country TLD according to IANA
                    $tlds = array(    'aero',    'arpa',    'asia',    'biz',    'cat',    'com',    'coop',    'edu',    'gov',    'info',    'jobs',    'mil',    'mobi',    'museum',    'name',    'net',    'org',    'post',    'pro',    'tel',    'travel',    'xxx',    );             
                    if (count($arr) > 2 && in_array($_sub[0], $tlds) !== false) {//special TLD don't have a country
                        array_shift($arr);
                    }
                }
                $debug ? print("<br>\n" .'[*] One level TLD: <strong>'.join('.', $_sub).'</strong> ') : false; //DEBUG
            }
            else { // more than 3 levels, something is wrong
                for ($i = count($_sub); $i > 1; $i--) 
                    $removed = array_shift($arr);

                $debug ? print("<br>\n" . '[*] Three level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false; //DEBUG
            }
        }
        elseif (count($arr) === 2) {
            $arr0 = array_shift($arr);     
            if (strpos(join('.', $arr), '.') === false
                        && in_array($arr[0], array('localhost','test','invalid')) === false) // not a reserved domain
            {
                $debug ? print("<br>\n" .'Seems invalid domain: <strong>'.join('.', $arr).'</strong> re-adding: <strong>'.$arr0.'</strong> ') : false; //DEBUG
                // seems invalid domain, restore it
                array_unshift($arr, $arr0);
            }
        }     

        $debug ? print("<br>\n".'<strong style="color:gray">&laquo;</strong> Done parsing: <span style="color:red">' . $original . '</span> as <span style="color:blue">'. join('.', $arr) ."</span><br>\n") : false; //DEBUG     
        return join('.', $arr);
    }


     //TEST
    $urls = array(
    'www.example.com' => 'example.com',
    'example.com' => 'example.com',
    'example.com.br' => 'example.com.br',
    'www.example.com.br' => 'example.com.br',
    'www.example.gov.br' => 'example.gov.br',
    'localhost' => 'localhost',
    'www.localhost' => 'localhost',
    'subdomain.localhost' => 'localhost',
    'www.subdomain.example.com' => 'example.com',
    'subdomain.example.com' => 'example.com',
    'subdomain.example.com.br' => 'example.com.br',
    'www.subdomain.example.com.br' => 'example.com.br',
    'www.subdomain.example.biz.br' => 'example.biz.br',
    'subdomain.example.biz.br' => 'example.biz.br',
    'subdomain.example.net' => 'example.net',
    'www.subdomain.example.net' => 'example.net',
    'www.subdomain.example.co.kr' => 'example.co.kr',
    'subdomain.example.co.kr' => 'example.co.kr',
    'example.co.kr' => 'example.co.kr',
    'example.jobs' => 'example.jobs',
    'www.example.jobs' => 'example.jobs',
    'subdomain.example.jobs' => 'example.jobs',
    'insane.subdomain.example.jobs' => 'example.jobs',
    'insane.subdomain.example.com.br' => 'example.com.br',
    'www.doubleinsane.subdomain.example.com.br' => 'example.com.br',
    'www.subdomain.example.jobs' => 'example.jobs',
    'test' => 'test',
    'www.test' => 'test',
    'subdomain.test' => 'test',
    'www.detran.sp.gov.br' => 'sp.gov.br',
    'www.mp.sp.gov.br' => 'sp.gov.br',
    'ny.library.museum' => 'library.museum',
    'www.ny.library.museum' => 'library.museum',
    'ny.ny.library.museum' => 'library.museum',
    'www.library.museum' => 'library.museum',
    'info.abril.com.br' => 'abril.com.br',
    '127.0.0.1' => '127.0.0.1',
    '::1' => '::1',
    );

    $failed = 0;
    $total = count($urls);

    foreach ($urls as $from => $expected){
        $from = get_domain($from, true);
        if ($from !== $expected){
            $failed++;
            print("<div style='color:fuchsia;'>expected {$from} to be {$expected}</div>");
        }
    }    
    if ($failed)    
        print("{$failed} tests failed out of {$total}");    
    else    
        print("Success");   

在需要检查“localhost”之前,我一直在使用Baptiste Donaux的版本。我认为Shanoop的版本更可靠

我在一个包含190个断言的测试套件中测试了这两个版本,对性能没有太大影响。如果仍然需要毫秒,您可以使用Redis或类似工具在生产中缓存结果

这是Shanoop答案的同一版本,但没有调试行,并且有一点清理:

function stripSubdomain($domain) 
{
    $domain = strtolower($domain);
    if (isIp($domain)) ? return $domain;
    return stripArray( buildArray($domain) );
}

function isIp($domain)
{
    return (filter_var($domain, FILTER_VALIDATE_IP));
}

function buildArray($domain)
{
    return array_slice(array_filter(explode('.', $domain, 4), function($value){
                                                                  return $value !== 'www';
                                                              }), 0);
}

function stripArray($arr)
{
    // TLD Domains
    if (count($arr) > 2) {
        $count = count($arr);
        $_sub = $this->retrieveSubdomain($arr);

        // two level TLD
        if (count($_sub) === 2)  {
            array_shift($arr);
            if ($count === 4) array_shift($arr);
        }

        // one level TLD
        elseif (count($_sub) === 1){
            $removed = array_shift($arr);
            if (strlen($_sub[0]) === 2 && $count === 3) array_unshift($arr, $removed);

            else {
                // non country TLD according to IANA
                $tlds = ['aero', 'arpa', 'asia', 'biz', 'cat', 'com', 'coop',
                         'edu', 'gov', 'info', 'jobs', 'mil', 'mobi', 'museum',
                         'name', 'net', 'org', 'post', 'pro', 'tel', 'travel', 'xxx'];

                if (count($arr) > 2 &&
                    in_array($_sub[0], $tlds) !== false) array_shift($arr);
            }

        }

        // more than 3 levels, something is wrong
        else
            for ($i = count($_sub); $i > 1; $i--) array_shift($arr);

    }

    // Special Domains
    elseif (count($arr) === 2) {
        $removed = array_shift($arr);
        $reserved = ['localhost','test','invalid'];
        if (strpos(join('.', $arr), '.') === false && in_array($arr[0], $reserved) === false)
            array_unshift($arr, $removed); // seems invalid domain, restore it
    }

    return join('.', $arr);
}

function retrieveSubdomain($arr)
{
    return explode('.', (count($arr) === 4 ? $arr[3] : $arr[2]) );
}

我更喜欢使用正则表达式来实现这一点,这对我来说更容易理解:

$url = "http://www.domain.com";
$parse = parse_url($url);
echo preg_replace("/^([a-zA-Z0-9].*\.)?([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z.]{2,})$/", '$2', $parse['host']); 

这一款适用于大多数领域,如果我自己也这么说的话,它会很优雅

public static function StripSubdomain($Domain) {

    $domain_array = explode('.', $Domain);
    $domain_array = array_reverse($domain_array);

    return $domain_array[1] . '.' . $domain_array[0];
}

这里有一个适用于所有域,包括那些具有二级域(如“co.uk”)的域


试试这个。我喜欢它的简单性,它在大多数用例中都对我有效

$domains = [
    "domain.com",
    "second.com",
    "www.third.com",
    "www.fourth.fifth.com",
    "openhours.colyn.dev"
];

$domains = array_map(function ($domain) {
    $parts = explode('.', $domain);
    return implode('.', array_slice($parts, count($parts)-2));
}, $domains);

/**
[
    "domain.com",
    "second.com",
    "third.com",
    "fifth.com",
    "colyn.dev",
]
*/

不是超级健壮,但对我来说,它运行良好。

关于
www.amazon.co.uk
?按照你的规则,应该是
co.uk
,这显然是错误的。你可能对这些作品感兴趣。谢谢巴蒂斯特!我只是不知道为什么。你能对代码稍加注释吗?特别是“echo…”行…正如Marc B在上面指出的,这将返回“co.uk”作为“amazon.co.uk”。如果你知道你的子域总是有一部分顶级域名,那么你很好,否则你将不得不创建可能的多部分顶级域名列表,并确保你没有剥离不应该剥离的内容。谢谢shanoop,对我不起作用,因为我检查了数百万个URL。。。所以这个版本会浪费我大量的脚本时间…@DoJoChi,如果你非常确定你有一百万个URL的可能性的话。然后你可以选择巴蒂斯特·多纳克斯的。该代码将在具有国家/地区TLD的域上失败。如果删除所有的测试和调试行,这个函数就行了。我实际上已经在一个类中实现了它。如果这样做,则只将第一个方法设为public(并使用$this->method调用其他方法)。此外,还有一些可能的改进需要完成,比如从类构造函数中获取域,然后只调用$domain=newdomain('url.here');然后是$domain->stripSubdomain();我使用区域文件,只在com/net中需要它=]regex非常棒而且是unitool!谢谢分享!这应该是接受答案,没有函数或从github拉取文件!难道
[a-zA-Z0-9][a-zA-Z0-9-]+
不会比
[a-zA-Z0-9][a-zA-Z0-9-]{1,61}
更优雅吗?这是目前为止最简单的方法。但是有一个小错误。例如,您的答案正确地解析了结尾处带有.co.uk的URL,但也有一些结尾带有like.com.au的URL,在这种情况下,这个正则表达式无法正确解析URL。值得称赞的是,这一个确实是最有效的。
public static function StripSubdomain($Domain) {

    $domain_array = explode('.', $Domain);
    $domain_array = array_reverse($domain_array);

    return $domain_array[1] . '.' . $domain_array[0];
}
function strip_subdomains($url){

    # credits to gavingmiller for maintaining this list
    $second_level_domains = file_get_contents("https://raw.githubusercontent.com/gavingmiller/second-level-domains/master/SLDs.csv");

    # presume sld first ...
    $possible_sld = implode('.', array_slice(explode('.', $url), -2));

    # and then verify it
    if (strpos($second_level_domains, $possible_sld)){
        return  implode('.', array_slice(explode('.', $url), -3));
    } else {
        return  implode('.', array_slice(explode('.', $url), -2));
    }
}
$domains = [
    "domain.com",
    "second.com",
    "www.third.com",
    "www.fourth.fifth.com",
    "openhours.colyn.dev"
];

$domains = array_map(function ($domain) {
    $parts = explode('.', $domain);
    return implode('.', array_slice($parts, count($parts)-2));
}, $domains);

/**
[
    "domain.com",
    "second.com",
    "third.com",
    "fifth.com",
    "colyn.dev",
]
*/