55502f40dc8b7c769880b10874abc9d0

A code block for php coders to get urls shorter. I hope you like it.

http://www.denizliozon.com

<?php
function shorturl($url){
    $length = strlen($url);
    if($length > 45){
        $length = $length - 30;
        $first = substr($url, 0, -$length);
        $last = substr($url, -15);
        $new = $first."[ ... ]".$last;
        return $new;
    }else{
        return $url;
    }
}
?>


//USAGE

<?php

$longurl= "http://www.google.com/search?q=refactormycode&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:tr:official&client=firefox-a";
$shorturl = shorturl($longurl);
echo "<a href=\"$longurl\">$shorturl</a>";


?>

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

Yacoby

May 25, 2010, May 25, 2010 09:23, permalink

2 ratings. Login to rate!
<?php
function shorturl($url){
    if( strlen($url) > 45){
        return substr($url, 0, 30).'[ ... ]'.substr($url, -15);
    }
    return $url;
}
?>
1bf59120892e34eb60836725566c6e55

fain182.myopenid.com

May 30, 2010, May 30, 2010 10:20, permalink

1 rating. Login to rate!
<?php
function shorturl($url){
    return strlen($url) > 45) ? substr($url, 0, 30).'[ ... ]'.substr($url, -15) : $url;
}
?>
8f3486a6fd9309188a9560d432bf046d

strager

June 12, 2010, June 12, 2010 21:00, permalink

No rating. Login to rate!

If a given string is 45 characters, your end up making the string longer. This code accounts for that.

<?php
function shorturl($url) {
    $midPart = '[ ... ]';
    $maxLength = 45;
    $minLeftLength = 25;

    if(strlen($url) > $maxLength) {
        $leftAndMid = substr($url, 0, $minLeftLength) . $midPart;
        $url = $leftAndMid . substr($url, -($maxLength - strlen($leftAndMid)));
        // or
        // $url = $leftAndMid . substr($url, -($maxLength - $minLeftLength - strlen($midPart));
    }

    return $url;
}
?>

Your refactoring





Format Copy from initial code

or Cancel