2012-09-27 32 views
1

这是我迄今为止的代码。如何从php/regex中删除域名中的TLD

$main = 'example.com'; 

$removed = str_ireplace("cant figure out what to put in here...", " ", "$main"); 
echo $removed;` 

我知道我可以只是把.COM第一paramerter但也有数百种不同的TLD的IM试图删除。

+0

只是问......为什么要从URL中删除TLD ...? –

+0

请看http://php.net/manual/en/function.preg-replace.php – Serge

+0

Bergi,我不是很擅长php,但我已经尝试过.com | .org等并不真的想这样做,因为有数百个。但它无功无用。我一整晚都在努力。弗雷德里克,我想删除它,所以我可以统计域名中的字符减去tld –

回答

1

使用parse_url可以删除URL,并且http-build-url可以在删除主机后进行备份。

一个简单的例子(警告 - 可能行不通,之后我会解释为什么)。

$url = "http://example.com:port/path?query=parts&so=on"; 
$aParts = parse_url($url); 
$aParts['host'] = ''; 
$removed = http_build_url($aParts); 
echo $removed; 

但是这可能不是原因有二:

  1. http_build_url并不总是安装在PHP的HTTP功能。您可能需要从PECL获得,但在此之前...
  2. 关于构建严格URL的功能非常繁琐,因此您可能希望自己实际创建它。

因此,一个更好的解决办法是:

$url = "http://example.com:port/path?query=parts&so=on"; 
$aParts = parse_url($url); 
$aParts['host'] = ''; 
$removed = ($aParts['host'] ? $aParts['host'] : 'http') . '://' 
      '' . // This is where the host goes 
      ($aParts['post'] ? ':' . $aParts['port'] : '') . 
      ($aParts['path'] ? '/' . $aParts['path'] : '') . 
      ($aParts['query'] ? '?' . $aParts['query'] : '') . 
      ($aParts['fragment'] ? '#' . $aParts['fragment'] : ''); 

(未测试 - 道歉对任何错误,但你shouldge的想法)

添加的用户,并通过必要时(检查文档上面链接),如果你想更换主机不留空白 - 你看看在哪里做。

+0

在第一次出现一段时间后,似乎需要做很多工作才能删除任何东西。url总是在没有http://没有子目录的情况下找到它,它始终是example.com example.org examp le.me example1.me example.co.uk我想要做的就是使用正则表达式代码在第一个之后删除任何东西。我开始认为正则表达式不能用于str_ireplace,这可能是我的问题。 –

+0

preg_replace或preg_match是你想要的正则表达式。 – Robbie

+0

或者你只有域名,而不是网址。在这种情况下,stristr()会为你创造奇迹。 – Robbie

1

这就是我想出的感谢robby指引我在正确的方向。

$ url ='example.com.uk';

$ removed = stristr($ url,'。',true);

echo“$ removed”;