dongshi1102 2015-12-22 21:19
浏览 19
已采纳

PHP修剪www如果存在并删除路径

I have an array of domain names, like:

array(
'http://example.co.uk/foo/bar',
'http://www.example.com/foo/bar',
'http://example.net/foo/bar')

And so on.

I am using

parse_url($url, PHP_URL_HOST);

to trim everything and just keep the domain name and it's working partly however, it's keeping the www part if it exists. How can I remove the 'www' if it exists. I tried to explicitly remove it from the domain name in the array, but when it resolves it reverts back to www.example.com.

So I'd like to return:

www.example.com/foo/bar > example
www.example.co.uk/foo/bar > example
example.com/foo/bar > example
example.net/foo/bar > example
  • 写回答

3条回答 默认 最新

  • duanpaxin3531 2015-12-22 21:41
    关注

    The function below is not a general purpose function to get the domain name or domain part of a FQDN. Rather it will return the first label (from left to right) if it is not www, and the second label if it is. As requested above.

    <?php
    
    function get_domain_from_host($host)
    {
        $parts = explode('.', $host);
        $domain = strpos($host, 'www') === 0
            ? next($parts)
            : current($parts);
    
        return $domain;
    }
    
    function test()
    {
        $urls_wanted = array(
            'http://www.example.com/foo/bar' => 'example',
            'http://www.example.co.uk/foo/bar' => 'example',
            'http://example.com/foo/bar' => 'example',
            'http://example.net/foo/bar' => 'example'
        );
    
        foreach($urls_wanted as $url => $wanted) {
            $host   = parse_url($url, PHP_URL_HOST);
            $domain = get_domain_from_host($host);
            print assert($wanted == $domain);
        }
    }
    
    test(); // Outputs: 1111
    

    Example use (copy the function above):

    $url    = 'http://www.example.com/foo/bar';
    $host   = parse_url($url, PHP_URL_HOST);
    $domain = get_domain_from_host($host);
    echo $domain; // output is 'example'.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭