Web Development

Recursive underscore to hyphen conversion rule for mod_rewrite

Today I got improved mod_rewrite rules for recursive pattern replacement for you :-)

History – when I started learning mod_rewrite almost 3 years ago I posted about a trick to convert all underscore in Movable Type to hyphens in Google-Optimizing entries for better keyword indexing from underscore to hyphen

While there are better ways in MT to do that today, the mod_rewrite lesson was learnt.

Last December (2005) I got a great comment from David Kaspar about how to optimize those mod_rewrite rules.

Today I found out that he mailed me directly and didn't post that on the blog :-) that's an e-mail lag – isn't it???

Quote:

Regarding supporting old archives, the following works a bit better:

  1. only provide [L] at the last line (the one with a single underscore)
  2. start with the line with the maximum underscores first

This will replace the underscores iteratively which I think will result in that you can replace twice as many underscores than you have in your longest statement

Example:

</p>

	<p>RewriteRule /a/(.<strong>)_(.</strong>)_(.*)$    /a/$1-$2-$3 [NC] </p>

	<p>RewriteRule /a/(.<strong>)_(.</strong>)$           /a/$1-$2      [NC,L]</p></p>

	<p><p>a_b_c_d => a_b-c-d => a-b-c-d</p>

	<p>

Remember that the maximum number for substitution is $9

Thanks a lot Dave – and remember to post your comments on the site next time :-)

Average rating
(1 vote)

Similar entries