将 URL 与缩短服务阵列进行匹配


Matching URLs against array of shortening services

请考虑以下URL列表:

1 http://www.cnn.com/international/stories/423423532
2 http://www.traderscreener.com/blah
3 http://is.gd/fsdaGdfd3
4 http://goo.gl/23V534
5 http://bit.ly/54HFD
6 http://stackoverflow.com/question/ask

我想将缩短的 URL 扩展为其原始形式:

$headers = get_headers($URL, 1);
if (!empty($headers['Location'])) {
  $headers['Location'] = (array) $headers['Location'];
  $URL = array_pop($headers['Location']);
}

但是,我需要将所有 URL 与一系列缩短服务相匹配:

$array(
  'is.gd', 'bit.ly', 'goo.gl', 'wibi.us', 'tinyurl.com' // etc
)

在这种情况下,这必须过滤掉 URL 3、4 和 5。我相信最简单的方法是抓住*** http://***/blah。由于我对使用正则表达式的经验很少,因此需要什么正则表达式?或者有没有更好的方法来解决这个问题?

到目前为止,最简单的方法是不建立黑名单。相反,请查询 URL 并查看它是否重定向。发送 HEAD 请求,并查找状态代码。如果是 3xx,则有一个重定向,因此您应该查找"位置"标头并将其用作新 URL。

preg_match('/^http:'/'/(is'.gd|bit'.ly|goog'.gl'|wibi'.us|tinyurl'.com)/i', $URL);

如果您确定 URL 将采用该格式,则可以使用 explode((。

$url = "http://bit.ly/54HFD";
$tem = explode("/", $url);
$needles = array(
  'is.gd', 'bit.ly', 'goo.gl', 'wibi.us', 'tinyurl.com' // etc
)
foreach($needles as $needle) {
         $res = strpos($tem[2], $needle);
         if ($res !== false) DO_SOMEHING
}