How do I create a URL shortener?

后端 未结 30 2684
我寻月下人不归
我寻月下人不归 2020-11-22 05:11

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to \"http://www.example.org/abcdef\

30条回答
  •  天命终不由人
    2020-11-22 05:37

    Here is my PHP 5 class.

    dictionary = str_split($this->dictionary);
        }
    
        public function encode($i)
        {
            if ($i == 0)
            return $this->dictionary[0];
    
            $result = '';
            $base = count($this->dictionary);
    
            while ($i > 0)
            {
                $result[] = $this->dictionary[($i % $base)];
                $i = floor($i / $base);
            }
    
            $result = array_reverse($result);
    
            return join("", $result);
        }
    
        public function decode($input)
        {
            $i = 0;
            $base = count($this->dictionary);
    
            $input = str_split($input);
    
            foreach($input as $char)
            {
                $pos = array_search($char, $this->dictionary);
    
                $i = $i * $base + $pos;
            }
    
            return $i;
        }
    }
    

提交回复
热议问题