Use hyphen in CodeIgniter URL

I normally like to use hyphens than underscores in URL. It looks more easier to read I think. But in CodeIgniter normally we can’t use hyphens in URL as hyphens isn’t allowed in function name or class name.

To solve this in CodeIgniter, so the correct function name is found from the uri segment, only one simple change needs to be made.

There are two easier way. First one is:
In system/libraries/Router.php find line 153 and change this line

$segments = $this->_validate_request($segments);


$segments = $this->_validate_request(str_replace(“-”, “_”, $segments));

Some people don’t want to edit core codes. In that case, we can use an alternative way.

You may also read:  Setup a web server in Linux Ubuntu

A better solution is to create a MY_Router.php file in your /application/core directory. In that file you can have the following code:

public function _set_request($segments){
// Fix only the first 2 segments
for($i = 0; $i < 2; ++$i){
$segments[$i] = str_replace('-', '_', $segments[$i]);

// Run the original _set_request method, passing it our updated segments.

This is a nicer solution, as it doesn’t alter any segments beyond the controller and method, which is generally what people are after.

You may also like...

Leave a Reply

%d bloggers like this: