检查正则表达式/ PHP代码URL是短网址

问题描述 投票:3回答:4

我试图创建一个PHP函数,将检查通行证网址是短网址。事情是这样的:

/**
 * Check if a URL is a short URL
 *
 * @param string $url
 * return bool
 */
function _is_short_url($url){
    // Code goes here
}

我知道,一个简单的和肯定的拍摄方式是检查301重定向,但该功能的目的是节省只是外部请求检查。也不应该对URL shortners作为列表功能检查将是一个规模较小,能够方法。

因此,有几个可能的检查,我在想:

  1. 总体URL长度 - 可能是30个字符最多
  2. 去年后“/” URL长度 - 可能是10个字符最多
  3. 的 '/' 后协议数(HTTP://) - 最大2
  4. 主机的最大长度

在一个可能的方法或更详尽的清单,这有什么想法?

编辑:此功能只是为了挽救外部请求,所以其确定为一个非短网址返回true(但一个真正的短单)。后通过这个功能,我想反正通过检查301个重定向展开所有短网址。这仅仅是消除明显的。

php regex url-shortener
4个回答
4
投票

我不建议使用正则表达式,因为这将是过于复杂,不易理解。这里是一个PHP代码来检查所有的约束条件:

function _is_short_url($url){
        // 1. Overall URL length - May be a max of 30 charecters
        if (strlen($url) > 30) return false;

        $parts = parse_url($url);

        // No query string & no fragment
        if ($parts["query"] || $parts["fragment"]) return false;

        $path = $parts["path"];
        $pathParts = explode("/", $path);

        // 3. Number of '/' after protocol (http://) - Max 2
        if (count($pathParts) > 2) return false;

        // 2. URL length after last '/' - May be a max of 10 characters
        $lastPath = array_pop($pathParts);
        if (strlen($lastPath) > 10) return false;

        // 4. Max length of host
        if (strlen($parts["host"]) > 10) return false;

        return true;
}

1
投票

这里是检查您的所有需求的一个小功能。我可以检查它不使用复杂的正则表达式,...只有使preg_split。你应该自己很容易适应它。

<?php

var_dump(_isShortUrl('http://bit.ly/foo'));

function _isShortUrl($url)
{
    // Check for max URL length (30)
    if (strlen($url) > 30) {
        return false;
    }

    // Check, if there are more than two URL parts/slashes (5 splitted values)
    $parts = preg_split('/\//', $url);
    if (count($parts) > 5) {
        return false;
    }

    // Check for max host length (10)
    $host = $parts[2];
    if (strlen($host) > 10) {
        return false;
    }

    // Check for max length of last URL part (after last slash)
    $lastPart = array_pop($parts);
    if (strlen($lastPart) > 10) {
        return false;
    }

    return true;
}

0
投票

如果我是你,我会测试,如果该URL显示了301重定向,然后测试,如果重定向重定向到另一个网站:

function _is_short_url($url) {
   $options['http']['method'] = 'HEAD';
   stream_context_set_default($options); # don't fetch the full page
   $headers = get_headers($url,1);
   if ( isset($headers[0]) ) {
     if (strpos($headers[0],'301')!==false && isset($headers['Location'])) {
       $location = $headers['Location'];
       $url = parse_url($url);
       $location = parse_url($location);
       if ($url['host'] != $location['host'])
         return true;
     }
   }

   return false;
}

echo (int)_is_short_url('http://bit.ly/1GoNYa');

0
投票

为什么不检查主机相匹配已知URL缩短。你冷得到最常见的网址缩短for example here的列表。

© www.soinside.com 2019 - 2024. All rights reserved.