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 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了