Using hyphens instead of underscores in CodeIgniter
When I’m building a CodeIgniter application there are several important things that I need to think about whilst putting the whole project together. Two of these things are Accessibility and Search Engine Optimisation (SEO) and in particular for this article the URLs I use to link it all together.
First, let’s take a look at a standard CodeIgniter URL.
http://www.example.com/example/hello_world
The first segment (example) normally refers to the controller that you are accessing. The second segment (hello_world) refers to the function in that controller that you want to execute in order to build the content that will be displayed. As you can see here our function is called hello_world() and uses an underscore to separate two words within the name. In terms of SEO and accessibility it is often better to use a hyphen (-) instead of an underscore (_) within an URL and one key reason for using the latter is that many applications and Search Engine Spiders such as Google interpret hyphens as spaces whilst underscores are often left as they are.
Using Codeigniter it is possible to convert the underscores in function names in to hyphens for URLs so that http://www.example.com/example/hello-world actually calls the function hello_world within our example controller. In order to do this you need to extend and alter the Codeigniter core Router class so that it’ll replace the hyphens within the URL with underscores during runtime. In order to achieve this you can use the code below.
Step 1. Create a custom Router file in ./application/core/ called MY_Router.php. If the core folder does not exist in your installation then create it.
Step 2. Insert the following code in to the file, save it and you’re done!
<?php
class MY_Router extends CI_Router {
function _set_request ($seg = array())
{
// The str_replace() below goes through all our segments
// and replaces the hyphens with underscores making it
// possible to use hyphens in controllers, folder names and
// function names
parent::_set_request(str_replace(‘-‘, ‘_’, $seg));
}
}