databaseslug

Generating unique slugs from titles


What's the best way to deal with slugs when it comes to repetition. Let's say for example the slug is for a blog post. It seems standard slug conversion seems to remove all non alphanumeric characters and then lower the case and lastly breaks spaces with either an under score or a hyphen. But there's issues, for example:

Titles => Slug

  1. Top 500 Sport Activities => top-500-sports-activities
  2. Top $500 Sports Activities => top-500-sports-activities

There's a slug duplication to two unique titles. Is there a method to getting around this? Perhaps simple safe symbol conversions?

However, I would like it to be able to same slug from each title given as a way to prevent duplication of post items.


Solution

  • You cannot obtain unique slugs in general because of the Pigeonhole Principle. You are mapping from a bigger set into a smaller one which implies duplicates.

    You can, of course, do tricks with symbols and try to insert underscores of dashes are already taken. That is not a general solution, though, because not all symbols can be used (there wouldn't be a need for a slug). You probably need to resort to adding another token to the URL like a date or a sequence number.