【问题标题】:Regular expression to replace a URL with just the domain name?正则表达式仅用域名替换 URL?
【发布时间】:2014-07-24 15:35:34
【问题描述】:

我想将任何 URL 作为输入,并仅输出域名,因此在 .com 或 .co.uk 等之后没有尾部斜杠)并删除 www。以及之前的任何内容(注意可能没有 www.)。

例子:

http://google.com/dir1/dir2/index.php -> google.com https://www.wonderfulworld.co.uk?a=1 -> wonderfulworld.co.uk

我将在 PHP 中使用preg_replace 方法。

【问题讨论】:

  • 发布所有可能的例子。
  • “我将在 PHP 中使用 preg_replace 方法。” - 哦?
  • @AvinashRaj URL 将作为用户输入,因此它可以是任何合法的 URL。
  • @Fred-ii- 不知道这有什么帮助?

标签: php regex replace preg-replace


【解决方案1】:

您可以使用 parse_url

而不是 preg_replace
$url = 'http://google.com/dir1/dir2/index.php';
$parse = parse_url($url);
print $parse['host'];

输出:

google.com

【讨论】:

  • 谢谢,我不知道这种方法。我需要稍微调整一下以删除 www 和 www3 等,但除此之外它是完美的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
相关资源
最近更新 更多