This page explains how to convert a string to slug in CodeIgniter. Slugifying is the action of converting a
string into a valid URL (a slug). For example : le blog à Lulu will become le-blog-a-lulu.
CodeIgniter is provided with helpers that can be used to slugify a string.
The following function converts a string into a slug:
$this->load->helper('text');
$this->load->helper('url');
$slug = url_title(convert_accented_characters($string), 'dash', true);
However, this functions does not fully support transliteration for foreign languages, especially french. As an example, apostroph, is removed from the string while it should be converted into separator.
The best option to fully support transliteration and add futur
unsupported characters is to 'extend' the URL helper. Create a new file named
MY_url_helper.php in application/helpers/.
Here is the content of the file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Check if the function does not exists
if ( ! function_exists('slugify'))
{
// Slugify a string
function slugify($string)
{
// Get an instance of $this
$CI =& get_instance();
$CI->load->helper('text');
$CI->load->helper('url');
// Replace unsupported characters (add your owns if necessary)
$string = str_replace("'", '-', $string);
$string = str_replace(".", '-', $string);
$string = str_replace("²", '2', $string);
// Slugify and return the string
return url_title(convert_accented_characters($string), 'dash', true);
}
}
Use the following code to slugify a string:
$this->load->helper('url_helper');
$slug = slugify ($string);