简体   繁体   中英

I need a regex to replace underscore by hyphen

I have a problem with my application. I use CodeIgniter for my project and it's forbidden to use hyphen in classname (underscores are allowed). But I want to separate words in URLs by hyphens. So I need to rewrite urls by a regex to replace underscores by hyphens in htaccess file. Ideas?

For example:

I have many links:

  • domain.tld/I_need_help

  • domain.tld/I_need_regex

I want to have:

  • domain.tld/I-need-help

  • domain.tld/I-need-regex

In htaccess file, there should be:

RewriteRule ^(.*)_(.*)$ /$1-$2

You are allowed to use routes to change url as you want.

$route['link-to_something'] = 'class_name/some_function';

after your edit: try this one:

RewriteRule ^([^_]*)_([^_]*_.*) $1-$2 [N]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]

Ok after a long search. I have the solution:

Go to Codeigniter Routes regex - using dashes in controller/method names

Why you are using regex when you can achieve this by changing just the one line?

Open application/config/routes.php and change

$route['translate_uri_dashes'] = TRUE;

That is it you need to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM