Create unique slugs for URLs using PHP and Python

With every geek on Quora, it has become a place where people are asking all kinds of weird questions and that too again and again. If anyone observes the URLs, you would notice something called slugs. Slugs in the URLs are SEO friendly. By SEO friendly, it means that a URL like http://xyz.com/what-is-spice-forms is much better than than an id based url like this http://xyz.com/post/4. The what-is-spice-forms portion in URL is called slug. It points to exactly /post/4 and hence, acts as an alias.

Clean URLs help search engines like Google, Bing to identify the content of the page (yes they are intelligent enough to understand English) and if searched for, it simply lists pages with these URLs on the top. In fact, Google uses gives preferences to the content of the URL while ranking results – this means that if the slug contains a search term, there is a probability that it would be ranked higher. The routing system of each framework is different and URLs can be stored with a matching value. For example, a URL like http://xyz.com/what-is-spice-forms is actually interpreted ashttp://xyz.com/post/4. It means visiting the not-so-friendly URL will also land you to same page.

There might be a case of ambiguity if someone asks the same question. Usually that time a database search is done and the URL is modified slightly to make it unique. For example, it can be observed that Facebook stores URL like http://xyz.com/what-is-spice-forms-12836. The last number is used to make the slug unique and it reduces a database query.

Overall, it can be concluded that slug based URLs are very constructive towards the popularity of the site.

PHP Slug Maker

We will discuss the slug maker in PHP. It is very easy to make a slug out of a given sentence or group of words. We are going to take inspiration from a gist and then slightly modify it to create unique URLs.

<?php
function slugify($str) {
    $search = array('Ș', 'Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', 'Â', 'Ă', 'ë', 'Ë');
    $replace = array('s', 't', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'E');
    $str = str_ireplace($search, $replace, strtolower(trim($str)));
    $str = preg_replace('/[^\w\d\-\ ]/', '', $str);
    $str = str_replace(' ', '-', $str);
    return preg_replace('/\-{2,}/', '-', $str);
}

This function generates a slug based out of the $str you pass to the function. A string like this The quick brown fox was slugified to the-quick-brown-fox. To make it unique, we will add a unique string at the end.

$url = slugify("The quick brown fox")."-".uniqid();

PHP uniqid()

uniqid() helps to generate a unique random string and the algorithm makes it almost unique. There are some params which can be passed to increase the likelihood of uniqueness but since we are already combining it with a slug, the total string being duplicate has inverse astronomical probability. In simple words, the slug generated will be unique. If you are using databasees, you can also append the primary key (ID) to the end of the string to make it unique.

Python

In python, a package already exists which makes slugs. You can install it using a package manager like pip.

pip install python-slugify

Usage:

txt = "This is a test ---"
r = slugify(txt) // gives 'this-is-a-test'

The unique ID can be attached using uuid() function and voila, the slug is created.

Python Django

If you are using Python Django, a package is available called django-autoslug which does exactly the same. Also, the [SlugField](https://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield)may be used to create slugs in models.

I hope the quest for creating unique slugs is over. Keep creating them!

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 6 = 10

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>