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 openwrt双栈NAT
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?
  • ¥15 (SQL语句|查询结果翻了4倍)
  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用