Generating string combinations for a url shortening service using PHP

Posted on 24/12/09 by webadmin No Comments

Url shortening is a technique in which a larger URL is made available by accessing a relatively shorter URL.  This is useful for sending links with via email, twitter,  sms etc.  Popular URL shortening services include tinyurl.com and bit.ly.

Usually, the long web page url is mapped to a randomly generated string-numeric combination such that by typing the
url http://shorteningservice.com/randomstring will redirect to the original long url.

I have made the generation of random strings in a uniform way using php by using the characters A to Z.
This is explained below (Usage Examples: 2). This method provides the user a chance to predict the next short url.

Usage Examples:

1. Permutation of strings:

permutations(”ABCDEF”, 3) will return an array of 130 string sequences from ABC to DEF.
This is the permutation of 6 charecters taken 3 at a time. Here ABC and ACB are taken as seperate entities.

2. Permutation with repetation:

That is a sequence of the form AAA, AAB, …., ZZZ, AAAA,AAAB,AAAC,…ZZZZ,…..,ZZZZZZZZZZ…ZZ.
I can show you a function that returns the next element of the above series when the current string is given.

Php Code:

<?php
//function to get the array permutation string sequences
function stringPermute($orgString,$num){
    $last = substr($orgString, 0, $num);
    $result = array();
    while($last != substr($orgString,  -$num)){
        $result[] = $last;
        $last = getNextString($orgString,$last,$num-1);
    }
    $result[] = $last;
    return $result;
}
//Function to get the next string sequence in order
function getNextString($fullString,$string,$char){
    if($string{$char} <> lastElement($fullString)){
        $string{$char} = $fullString{strpos($fullString,$string{$char})+1};
        return $string;
    }else{
        $string = change($string,$fullString{0},$char);
        return getNextString($fullString,$string,$char-1);
    }
}

function lastElement($string){
    return $string{strlen($string)-1};
}

function change($string,$char,$start = 0,$end = 0){
    if($end == 0)
        $end = strlen($string)-1;
    for($i=$start;$i<=$end;$i++){
        $string{$i} = $char;
    }
    return $string;
}
?>

Post a Comment

Your email is never published or shared. Required fields are marked *