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 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃