dpp89959 2015-09-17 19:12
浏览 123
已采纳

PHP从网址中删除域名

I know there is a LOT of info on the web regarding to this subject but I can't seem to figure it out the way I want.

I'm trying to build a function which strips the domain name from a url:

http://blabla.com    blabla
www.blabla.net       blabla
http://www.blabla.eu blabla

Only the plain name of the domain is needed.

With parse_url I get the domain filtered but that is not enough. I have 3 functions that stips the domain but still I get some wrong outputs

function prepare_array($domains)
{
    $prep_domains = explode("
", str_replace("", "", $domains)); 
    $domain_array = array_map('trim', $prep_domains); 

    return $domain_array;
}

function test($domain) 
{
    $domain = explode(".", $domain);
    return $domain[1];
}

function strip($url) 
{ 
   $url = trim($url);
   $url = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url); 
   $url = preg_replace("/\/.*$/is" , "" ,$url); 
   return $url; 
}

Every possible domain, url and extension is allowed. After the function is finished, it must return a array of only the domain names itself.

UPDATE: Thanks for all the suggestions!

I figured it out with the help from you all.

function test($url) 
{   
    // Check if the url begins with http:// www. or both
    // If so, replace it
    if (preg_match("/^(http:\/\/|www.)/i", $url))
    {
        $domain = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
    }
    else
    {
        $domain = $url;
    }

    // Now all thats left is the domain and the extension
    // Only return the needed first part without the extension    
    $domain = explode(".", $domain);

    return $domain[0];
}
  • 写回答

5条回答 默认 最新

  • dpli36193 2015-09-18 19:21
    关注
    function test($url) 
    {   
        // Check if the url begins with http:// www. or both
        // If so, replace it
        if (preg_match("/^(http:\/\/|www.)/i", $url))
        {
            $domain = preg_replace("/^(http:\/\/)*(www.)*/is", "", $url);
        }
        else
        {
            $domain = $url;
        }
    
        // Now all thats left is the domain and the extension
        // Only return the needed first part without the extension    
        $domain = explode(".", $domain);
    
        return $domain[0];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看