How to : Replace underscore “_” with hyphen “-” in CodeIgniter

Hello there,

Since last couple of days I am aware of on-site SEO. There I found that underscore in URL is not recommended rather hyphen is good for SEO. But in PHP class method hyphen is not allowed rather underscore is recommended. So when you make a method in controller class over CI its difficult to map that method with hyphen. Generally you can declare that in config/routes.php but its a pain in ass when you have a lot of methods which have underscore in that.

I am searching for a general approach to accomplish this solution and the best way IMO is extend the Core Router and replace all the request of hyphen with underscore so that CI can map your hyphen URL with underscore method name. Well here goes the code,

<?php
defined('BASEPATH') || exit('No direct script access allowed');
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));
}
}

Name this file My_Router.php and put it in application/core folder. No worries guys it will auto-load in your latest CI (2.1.4) installation.

Hope this simple tweak can optimize your on-site SEO.

Have a good days friends. 🙂

(Visited 48 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *