views:

87

answers:

3

This is the code I use,

<IfModule mod_rewrite.c>
 RewriteCond %{SCRIPT_FILENAME} !-d
 RewriteCond %{SCRIPT_FILENAME} !-f
 RewriteRule ^([^/]+)/?([^/]+) index.php?user=$1&do=$2 [L]
</IfModule>

if i give it abcd/1234 it will capture abcd first then 1234 as the second variable. But if the url was abcd/ or abcd the first capture stays the same, yet the second capture becomes d. This would cause no problem in the php code itself, yet it would be more efficient if it was not captured in the first place.

oh to clarify, neither the first or second capture are required for the index.php page. But will change its purpose if they exist.

any help with the regex code would be appreciated, and if there are anyways to improve it more or write it more efficiently i would be very grateful to know!

Thank You very Much : )
i use this tool http://gskinner.com/RegExr/ to check this.

A: 

The question mark in the rule along with the second plus sign is causing it to be split this way. You should remove the question mark since you already require at least one character in the second group.

Edit: In that case, use this:

RewriteRule ^([^/]+)(/([^/]+))?$ index.php?user=$1&do=$3 [L]
Ignacio Vazquez-Abrams
i will check that! just to make clear neither the first or second capture are required, thank you though : )
Mohammad
A: 

Very simple modification:

 ^([^/]+)/?([^/]*)
KiNgMaR
worked :D do you see any room for code improvement? And do you know why the previous code would capture only the d? thank you!
Mohammad
+1  A: 

The second part ($2) is non-optional because you wrote [^/]+. I would replace the whole thing by ^([^/]+)(?:/([^/]+))? which leads to the following results:

abcd -> $1='abcd' $2=''

abcd/ -> $1='abcd' $2=''

abcd/something -> $1='abcd' $2='something'

AndiDog
the regex you provided also works! is there anyway to know which of the working codes, yours and ^([^/]+)/?([^/]*) is more efficient in this case? thank you for the explanation.
Mohammad
I just ran a test using Python's re module (with compiled regexes, doing 10000000 matches on short example URLs like "abcdefg/bam"). My regex took 54 seconds, while KiNgMaR's regex took 45 seconds. Kinda expected this... As both regexes are correct, you should go with the faster one ;)
AndiDog
that's an amazing test AndiDog, thank you for the effort and clarification, very appreciated!
Mohammad
No problem. Actually I was very curious about the performance results, too ;)
AndiDog