Jump to content

Shortening urls


sx

Recommended Posts

I am trying to shorten urls output.  What I want to do is if the url is more than 50 characters long I want it to shorten it by taken the necessary characters out of the middle of it.  I did this code

 

function shortenurl($link) {
if(strlen($link) > 50) {
$parsedhost =  parse_url($link, PHP_URL_HOST);
$parsedpath =  parse_url($link, PHP_URL_PATH);
$hostlength = strlen($posthost);
$pathlenth = strlen($parsepath);
$difference = 50 - $hostlength;
$sspath = substr("$parsedpath", -$difference);
echo "$link<br />";
echo "http://$parsedhost/...$sspath";
} ELSE {
echo "$link"; 
}}

 

$link is an actual url like

http://up-file.com/download/f8976a276795/MV.12.US.BY.SOFT-BEST.NET.exe.html

 

Here are some of the inputs and outputs I am getting.

 

 


Input:
http://rapidshare.com/files/23107332/tibw.part01.rar
Output:
http://rapidshare.com/.../files/23107332/tibw.part01.rar

Input:
http://www.mytempdir.com/1039456
Ouput:
http://www.mytempdir.com/1039456

Input:
http://up-file.com/download/f8976a276795/MV.12.US.BY.SOFT-BEST.NET.exe.html
Output:
http://up-file.com/...ad/f8976a276795/MV.12.US.BY.SOFT-BEST.NET.exe.html

 

I am wanting the maximum character length to be 50.  Or it will shorten it to 50 characters. If it is less than 50 then I want it to just echo the full url.

Link to comment
https://forums.phpfreaks.com/topic/45453-shortening-urls/
Share on other sites

if (($length = strlen($url)-50) > 0) $url = preg_replace('|(http://.+?/).{'.($length+3).'}(?:.*?(?=/))?(.*)|','$1...$2',$url);

 

The above one-liner works nicely except in the case of domain names longer than 40(or so?) characters.  I haven't tried to solve that caveat yet, though.

Link to comment
https://forums.phpfreaks.com/topic/45453-shortening-urls/#findComment-221508
Share on other sites

Okay, updated code...

 

Complicated:  assuming you want the code to attempt to break the URLs at slashes, if possible, and to leave the domain name intact, if possible, this is probably what you want:

if (($length = strlen($url)-50) > 0) $url = preg_replace('%(?(?=http://[^/]{42,}?/)(.{24}).*?(.{23}$)|(http://.+?/).{'.($length+3).'}(?:.*?(?=/))?(.*))%','$1$3...$2$4',$url);

It uses a conditional pattern to handle long domain names and worked quite nicely on my various test URLs.

 

Simple:  As above poster suggested, using a substr()-like function, this will cut out enough characters starting just after the "http://" prefix:

if (($length = strlen($url)-50) > 0) $url = substr_replace($url,'...',7,$length + 3);

Link to comment
https://forums.phpfreaks.com/topic/45453-shortening-urls/#findComment-221581
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.