Anybody great with regular expressions? (simple question)

KevySaysBeNice

[H]ard|Gawd
Joined
Dec 7, 2001
Messages
1,452
Hi all!

I am going a bit crazy by what I think should be a simple regular expression issue.

Here is the task: we want to take this:
/ts/123/32/1
and rewrite it to
/themes/index.php?t=$1&d=$2&r=$3

except, here is the catch: we want the last parameter to be totally optional. In most cases the final /1 won't be there, so if it's not there we don't want the rewrite rule to break.

Anyway, this is what we have so far and it works to get the first number (123) and the second (32).

/ts.*/(\d+)\/(\d+)$

BUT, I'm not sure how to get the last value, and make it optional.

Anybody have any pro tips?

Thanks in advance!!!
 
just have two regular expressions that are easy to read instead of one uber regex thats impossible to debug

test for
Code:
m?\^/ts/(\w*)/(\w*)/(\w*)$?
if it fails, test for the one without the end and do a repalce on that. CPU time is cheap.

I used ? on the ends because in perl you can deliniate your regexes with whatever characters you feel like.

otherwise :

Code:
m?/ts/(\w*)/(\w*)($|/(\w*)$)?
should work
 
I assume you're using mod_rewrite. Just use two rules. One to catch when the ending isn't there (that gets run first) and one to catch when it is.
 
Back
Top