如何最小化搜索结果中的URL链接

时间:2012-04-04 09:08:05

标签: php search

我有一个像

这样的搜索结果
  
    

1。我的头衔
    我的简短说明......     
http://www.stackoverflow.com/tags/thisthat/againthisthat/againandagainthisthat/mypage.html     
    http://www.stackoverflow.com/tags/mypage.html?a=123123123&b=2342343

  

我想要这种格式的网址

  
    

1。我的头衔
    我的简短说明......     
http://www.stackoverflow.com/tags/......./againandagainthisthat/mypage.html
    http://www.stackoverflow.com/tags/mypage.html?a....3123&b=2342343

  

链接中间会跳过某些文字

我试图谷歌但不知道要搜索的确切关键字..

我的链接是什么,如果该链接的长度超过70个字符,可以说它有100个,那么链接最小化为70个字符,中间位置..... ....强>

2 个答案:

答案 0 :(得分:1)

这适用于(原始示例):

$url = 'http://www.stackoverflow.com/tags/thisthat/againthisthat/againandagainthisthat/mypage.html';
$urlBitsArray = explode('/', $url);
$urlBitsCount = count($urlBitsArray);
$newUrl = implode('/', array($urlBitsArray['0'], $urlBitsArray['1'], $urlBitsArray['2'], $urlBitsArray['3'], '.....', $urlBitsArray[$urlBitsCount - 2], $urlBitsArray[$urlBitsCount - 1]));
echo $newUrl;

基本如果超过70个采用前32个字符,最后32个字符和'......'在中间:

$url = 'http://www.stackoverflow.com/tags/thisthat/againthisthat/againandagainthisthat/mypage.html ';

if (strlen($url) > 70) {
    $url = substr($url, 0, 31).'......'.substr($url, strlen($url) - 33);
}

echo $url;

答案 1 :(得分:0)

<?php
$string = "http://www.stackoverflow.com/tags/thisthat/againthisthat/againandagainthisthat/mypage.html";
$maxStringLength = 50;

if(strlen($string) > $maxStringLength)
{
    //remove http://
    if(strpos($string, "http://") === 0)
    {
        $string = substr($string, 7);
    }
    $bits = explode("/", $string);
    if(count($bits) > 2) //greater than www.stackoverflow.com/mypage.html
    {
        $string = implode("/", array($bits[0], $bits[1], '...', $bits[count($bits)-2], $bits[count($bits)-1]));
    }
}

echo $string;