0

我有一个存储个人网站网址的数据库表列。这个专栏是独一无二的,因为我不希望人们两次使用同一个网站!

然而,一个人可以通过这样做来解决这个问题:

domain.com
domain.com/hello123
www.domain.com

所以我的计划是这样当一个人保存他们的记录时,它会在第一个斜线之后删除所有内容,以确保只有域被保存到数据库中。

我该怎么做呢?我假设这已经做过很多次了,但我正在寻找一些非常简单的东西,并且对使用库或其他长代码片段不感兴趣。只是去除其余部分并仅保留域名的东西。

4

4 回答 4

5

PHP:parse_url

// Force URL to begin with "http://" or "https://" so 'parse_url' works
$url = preg_replace('/^(?!https?:\/\/)(.*:\/\/)/i', 'http://', $inputURL);
$parts = parse_url($url);
// var_dump($parts); // To see the parsed URL parts, uncomment this line
print $parts['host'];

请注意,使用列出的代码,子域不是唯一的。www.domain.com并且domain.com将是单独的条目。

于 2012-08-19T20:14:14.527 回答
3

使用parse_url

$hostname = parse_url($userwebsite,PHP_URL_HOST);
于 2012-08-19T20:16:00.330 回答
2
$sDomain = NULL;

foreach (explode('/', $sInput) as $sPart) {
  switch ($sPart) {
    case 'http:':
    case 'https:':
    case '':
      break;

    default:
      $sDomain = $sPart;
      break 2;
  }
}

if ($sDomain !== NULL) {
  echo $sDomain;
}

First, all slashes are used as separators. Next, all "known/supported" schemes are ignored, as well as the empty part which happens from "http://". Finally, whatever is next will be stored in $sDomain.

If you do not mind the dependency of PCRE, you can use a regular expression as well:

if (preg_match('/^https?:\/\/([^\/]+)/', $sInput, $aisMatch) === 1) {
  echo $aisMatch[1];
}
于 2012-08-19T20:18:21.687 回答
1

你可以试试

int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

然后将结果放入

string substr ( string $string , int $start [, int $length ] )

使用$needle = "/"$needle = "."

于 2012-08-19T20:13:46.673 回答