Home > other >  How to use regex to match a group multiple times
How to use regex to match a group multiple times

Time:05-18

Sorry for the bad title, I didn't know how to word this properly. I have a URL such as /colour-white/size-large/, and I need to rewrite it in htaccess. String should look like &colour=white&size=large after regex.

I don't want to have to make multiple rewrites for colour, size, colour and size.

I've come up with (colour|size)-(.*?)\/ on string colour-white/size-large/ with a substitution of $1=$2& which returns colour=white&size=large&, but it breaks when there's a / at the start, and I don't want the final string to have a trailing &.

Edit: \/*(colour|size)-(.*?)\/ &$1=$2 works, but it breaks once there's other text before it, I guess because with the global option it tries to match the before text each time it looks for colour or size.

CodePudding user response:

It is pretty common to add multiple rewrite rules for different numbers of parameters. This works, including what comes before it ("dresses") for up to three parameters. Adding a 4th parameter is just a fourth line. The number of rules needed increases linearly with the number of parameters, not exponentially.

RewriteEngine on
RewriteRule /?(.*/)?(colour|size|rarity)-([^/] )/(colour|size|rarity)-([^/] )/(colour|size|rarity)-([^/] )/ $1?$2=$3&$4=$5&$6=$7 [L]
RewriteRule /?(.*/)?(colour|size|rarity)-([^/] )/(colour|size|rarity)-([^/] )/ $1?$2=$3&$4=$5 [L]
RewriteRule /?(.*/)?(colour|size|rarity)-([^/] )/ $1?$2=$3 [L]

Another approach is to pass all of it as a single parameter and parse it in your handler. It is much cleaner to do parsing of arbitrary parameters in PHP, Java, Perl or whatever your back end language happens to be. This code would put an arbitrary number of them into the "options" parameter to be parsed on the back end:

RewriteEngine on
RewriteRule /?(.*/)?(colour|size|rarity-[^/] /)  $1?options=$2 [L]

You should also take a step back and ask if this is something you actually want or need to be doing. Sticking arbitrary parameters into the URL path is no more SEO friendly than having them in the query string. Your best URL may actually be /dresses?size=large&colour=blue You can read my full reasoning in my answer to SEO-friendly way to pass multiple values in a URL parameter

  • Related