How to create slug in codeigniter?

A slug is a part of the URL when you are accessing a resource. in this tutorial we are creating a slug by using the helper function.

Create a controller

File Name : Slug_controller.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Slug_controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Auth_model');
$this->load->helper('common');
$this->load->helper('text');
$this->load->helper('url');
}

public function index()
{
$this->load->view('slug-view');
}


public function save_slug()
{
$title = $this->input->post('title');
//echo $slug = slug($title); // call slug helper function
echo $slug = slugify($title); // call slugify helper function

}

}

create a common helper file

File Name : common_helper.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function slug($string, $spaceRepl = "-")
{
$string = str_replace("&", "and", $string);
$string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);
$string = strtolower($string);
$string = preg_replace("/[ ]+/", " ", $string);
$string = str_replace(" ", $spaceRepl, $string);
return $string;
}



// 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);
}
}




create view

File Name : slug-view.php

<html>
<head>
<title> </title>
</head>
<body>
<form name="frm" method="post" action="<?php echo base_url()?>slug_controller/save_slug">
<label>Title</label><input type="text" name="title" id="title"/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here