Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx match replace help

I am trying to do a regex match and replace for an .htaccess file but I can't quite figure out the replace bit. I think I have the match part right, but maybe someone can help.

I have this url- http://www.foo.com/MountainCommunities/Lifestyles/5/VacationHomeRentals.aspx

And I'm trying to turn it into this- http://www.foo.com/mountain-lifestyle/Vacation-Home-Rentals.aspx

(MountainCommunities/Lifestyles)/\d/(.*)(.aspx)

and then I figured I would have a rewrite rule starting like this-

mountain-lifestyle/$2$3

but I need to take what is in $2 in this instance and rewrite it to place dashes between the words with capital letters. Now I'm stumped.

like image 651
Marty Avatar asked Jul 17 '26 23:07

Marty


2 Answers

I think you'll have to do it in two bits... Take out $2, precede every capital (apart from the first) with a -, then use just append the result to http://www.foo.com/mountain-lifestyle/ with a .aspx on the end.

like image 119
Ben Avatar answered Jul 19 '26 11:07

Ben


Try this:

RewriteRule ^(([A-Z][a-z]+-)*)([A-Z][a-z]+)(([A-Z][a-z]+)+)(\.aspx)?$ /$1$3-$4 [N]
RewriteRule ^([A-Z][a-z]+-)+[A-Z][a-z]+$ /$0.aspx [R=301]

Note that mod_rewrite uses an internal counter to detect and avoid infinit loops. So your URL may not contain too much words having to be converted (see MaxRedirects option for Apache < 2.1 and LimitInternalRecursion directive for Apache ≥ 2.1).

like image 42
Gumbo Avatar answered Jul 19 '26 13:07

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!