Mevia
Mevia

Reputation: 1564

Regex for htaccess that matches multiple words split by hyphen

For now I'm using this htaccess file in my e-shop script:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/([\w-]+)/?$ product.php?category_id=$1&product_id=$2 [QSA,L]
RewriteRule ^([\w-]+)/?$ products.php?category_id=$1 [QSA,L]

It seems SEO friendly and is allowing customer to see nicely printed address bar like:

mydomain.com/CDPlayers/Sonytr200

The problem is that I was told to improve engine so instead of CDPlayers or Sonytr200 I should produce CD-Players and Sony-tr-200. I have to admit that I got that htaccess regex from the web, because I didn't study regex much.

This one isn't working anymore due to fact that it is accepting only one word and now I need something that will allow me to use unlimited number of words split by hyphen so it has to work in following cases:

or

and

or

Upvotes: 1

Views: 635

Answers (1)

anubhava
anubhava

Reputation: 784918

You can have a new recursive rule to remove all hyphens first:

RewriteEngine On

RewriteRule "^([^-]*)-+([^-]*-.*)$" $1-$2 [L]
RewriteRule "^([^-]*)-([^-]*)$" /$1-$2 [L,R=302]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/([\w-]+)/?$ product.php?category_id=$1&product_id=$2 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ products.php?category_id=$1 [QSA,L]

Upvotes: 2

Related Questions