减少链接(URL)大小

时间:2013-01-03 08:29:19

标签: php javascript url hyperlink reduce

是否可以通过PHP或JS减少链接的大小(以文本形式)?

E.g。我可能有这样的链接:

http://www.example.com/index.html                     <- Redirects to the root
http://www.example.com/folder1/page.html?start=true   <- Redirects to page.html
http://www.example.com/folder1/page.html?start=false  <- Redirects to page.html?start=false

目的是找出链接是否可以缩短并仍然指向同一位置。在这些示例中,前两个链接可以减少,因为第一个指向根,第二个指向可以省略的参数。
那么第三个链接是这样的情况,其中参数不能被省略,这意味着它不能进一步减少而不是删除http://

所以上面的链接会像这样减少:

Before: http://www.example.com/index.html
After:  www.example.com

Before: http://www.example.com/folder1/page.html?start=true
After:  www.example.com/folder1/page.html

Before: http://www.example.com/folder1/page.html?start=false
After:  www.example.com/folder1/page.html?start=false

这可能是PHP还是JS?

注意:

www.example.com不是我拥有的域名,也不是通过URL访问的域名。链接可能是未知的,我正在寻找类似于自动链接缩短器的东西,可以通过获取URL而不是其他任何东西。

实际上我在考虑类似于linkchecker的东西,它可以检查链接在自动修剪之前和之后是否有效,如果没有,那么将在链接的修剪版本上再次进行检查。但这似乎有点过分......

3 个答案:

答案 0 :(得分:1)

由于您希望自动执行此操作,并且您不知道参数如何更改行为,因此您必须通过反复试验来执行此操作:尝试从URL中删除部件,并查看服务器是否响应另一页。

在最简单的情况下,这可能会以某种方式工作:

<?php
    $originalUrl = "http://stackoverflow.com/questions/14135342/reduce-link-url-size";

    $originalContent = file_get_contents($originalUrl);

    $trimmedUrl = $originalUrl;

    while($trimmedUrl) {
        $trialUrl = dirname($trimmedUrl);
        $trialContent = file_get_contents($trialUrl);
        if ($trialContent == $originalContent) {
            $trimmedUrl = $trialUrl;
        } else {
            break;
        }
    }

    echo "Shortest equivalent URL: " . $trimmedUrl;
    // output: Shortest equivalent URL: http://stackoverflow.com/questions/14135342
?>

对于您的使用场景,您的代码会更复杂一些,因为您必须依次测试每个参数以查看是否有必要。有关起点,请参阅parse_url()parse_str()函数。

提醒一句:此代码非常慢,因为它会对您要缩短的每个URL执行大量查询。此外,它可能无法缩短许多URL,因为服务器可能在响应中包含诸如时间戳之类的内容。这使问题变得非常困难,这就是为什么谷歌等公司有许多工程师会考虑这样的事情的原因:)。

答案 1 :(得分:0)

是的,这是可能的:

JS:

var url = 'http://www.example.com/folder1/page.html?start=true';
url = url.replace('http://','').replace('?start=true','').replace('/index.html','');

PHP:

$url = 'http://www.example.com/folder1/page.html?start=true';
$url = str_replace(array('http://', '?start=true', '/index.html'), "", $url);

array()中的每个项目都将替换为""

答案 2 :(得分:0)

这是给你的JS。

function trimURL(url, trimToRoot, trimParam){
    var myRegexp = /(http:\/\/|https:\/\/)(.*)/g;
    var match = myRegexp.exec(url);
    url = match[2];
    //alert(url);  // www.google.com
    if(trimParam===true){
        url = url.split('?')[0];
    }
    if(trimToRoot === true){
        url = url.split('/')[0];
    }
    return url
}

alert(trimURL('https://www.google.com/one/two.php?f=1'));
alert(trimURL('https://www.google.com/one/two.php?f=1', true));
alert(trimURL('https://www.google.com/one/two.php?f=1', false, true));

小提琴:http://jsfiddle.net/5aRpQ/