Regex with RewriteRule

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Regex with RewriteRule

Post 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?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

is the id numerical? If so you should search for that

([0-9]+)
HiddenS3crets
Forum Contributor
Posts: 119
Joined: Fri Apr 22, 2005 12:23 pm
Location: USA

Post by HiddenS3crets »

that fixed the problem, but I still don't understand why the / was being included in $2 when it was (.*)
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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 (.*?)
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I find the \w and \d character classes (word and digit character, respectively) really useful in situations like this.

Cheers,
Kieran
Post Reply