1

有人可以帮我用正则表达式(我在 php 和 js 中需要它)来删除 http:// 和 www。从 url 字符串的开头并删除尾随 / 如果它在那里。

例如

  • http://www.google.com/将会google.com
  • https://yahoo.com?page=1 将会yahoo.com?page=1
  • fancysite.com/articles/2012/将会 fancysite.com/articles/2012

这是我用于 JS 端的代码:

row.page_href.replace(/^(https?|ftp):\/\//, '')

这是我用于 php 端的代码:

$urlString = rtrim($urlString, '/');
$urlString = preg_replace('~^(?:https?://)?(?:www[.])?~i', '', $urlString);

如您所见,JS 正则表达式当前仅删除 http://,而 php 需要两个步骤来完成所有操作。

4

2 回答 2

4
function cleanUrl($url)
{
  if (($d= parse_url($url)) !== false) // valid url
  {
    return sprintf('%s%s%s',
      ltrim($d['host'], 'www.'),
      rtrim($d['path']. '/'),
      !empty($d['query']) ? '?'.$d['query'] : '');
  }
  return $url;
}

我会利用parse_url(验证 url 以及“清理”它)

于 2012-12-28T16:43:29.320 回答
0

#(https?(://))?(www.?)?(.*)#i

对我来说工作得很好。您可以更改最后一个(.*)以匹配 URL 的 RFC 标准。

输出:

david@david-desktop ~ $ php -a
Interactive shell

php > $str = preg_replace('#(https?(://))?(www.?)?(.*)#i', '$4', 'https://www.google.ca');
php > echo $str . PHP_EOL;
google.ca
php > $str = preg_replace('#(https?(://))?(www.?)?(.*)#i', '$4', 'https://google.ca');
php > echo $str . PHP_EOL;
google.ca
php > $str = preg_replace('#(https?(://))?(www.?)?(.*)#i', '$4', 'http://google.ca');
php > echo $str . PHP_EOL;
google.ca
php > 
于 2012-12-28T16:42:04.517 回答