Page 1 of 1

Regex with RewriteRule

Posted: Sat Dec 16, 2006 5:12 pm
by HiddenS3crets
In my .htaccess file I use a RewriteRule as follows:

Code: Select all

RewriteRule ^([^images][A-Za-z]*)/(.*)/? index.php?section=$1&id=$2
This says to match a url like this:

Code: Select all

www.site.com/aSection/anID
and redirect it to:

Code: Select all

index.php?section=aSection&id=anID
The problem that I'm having is that if at the end of the URL there's a /, it becomes part of the ID, like this:

Code: Select all

URL is www.site.com/aSection/anID/
instead of having ...id=anID, I'm getting id=anID/

In my regex the / isn't inside the parentheses so I don't understand why it's being saved as part of backreference $2.

Any ideas?

Posted: Sat Dec 16, 2006 5:16 pm
by John Cartwright
is the id numerical? If so you should search for that

([0-9]+)

Posted: Sat Dec 16, 2006 5:26 pm
by HiddenS3crets
that fixed the problem, but I still don't understand why the / was being included in $2 when it was (.*)

Posted: Sat Dec 16, 2006 6:00 pm
by John Cartwright
HiddenS3crets wrote:that fixed the problem, but I still don't understand why the / was being included in $2 when it was (.*)
because it is greedy, and will match as far down the string as it possibly can. You would use a ? to make it un-greedy, as in (.*?)

Posted: Sat Dec 16, 2006 6:38 pm
by Kieran Huggins
I find the \w and \d character classes (word and digit character, respectively) really useful in situations like this.

Cheers,
Kieran