CodeIgniter Slug Library

I am happy to announce a simple CodeIgniter library to help you generate slugs for your urls. This is something I use on almost every project and it has been invaluable to me. Hopefully you will find it useful as well.

For those that are not familiar with the term slug WordPress defines it as:

A slug is a few words that describe a post or a page. Slugs are usually a URL friendly version of the title.

Description

What this library does is allow you to pass a string such as a titile and then generate a url friendly string from it. Also and most importantly it checks against fields in your db so that you will not have any duplicates. For example:

"This is my title"

Would become:

"this-is-my-title"

If a duplicate is found then it appends a number. Example:

"this-is-my-title-1"

Example

First load the library with an array of config items:

$config = array(
    'table' => 'mytable,
    'id' => 'id',
    'field' => 'uri',
    'title' => 'title',
    'replacement' => 'dash' // Either dash or underscore
);
$this->load->library('slug', $config);

When creating a uri for a new record in your db you can do it like this:

$data = array(
    'title' => 'My Test',
);
$data['uri'] = $this->slug->create_uri($data);
$this->db->insert('mytable, $data);

Then for when you are editing an existing record: (Notice the create_uri uses the second param to compare against other fields).

$data = array(
    'title' => 'My Test',
);
$data['uri'] = $this->slug->create_uri($data, $id);
$this->db->where('id', $id);
$this->db->update('mytable', $data);

Download

You can clone the repo by running the code below:

$ git clone git://github.com/ericbarnes/CodeIgniter-Slug-Library

Or visit the GitHub Repo.

CodeIgniter Slug Library