Jump to content

Optional regular expression ending


BluMess

Recommended Posts

Hi,

 

On my website I want users to be able to access:

/view_media.php?type=[whatever the media type is]

 

through this:

/games/

goes to

/view_media.php?type=1

 

/toons/

goes to

/view_media.php?type=2

 

HOWEVER on the end of the normal URL gets added some extra parameters for the script, lets just call them 'a' and 'b'.

/view_media.php?type=1&a=foo&b=bar

This would be accessible via

/games/&a=foo&b=bar

 

The .htaccess line I have is:

 

RewriteRule ^games/([^/\.]+)/?$ /view_media.php?type=1$1 [L]

where the regex part is the parameters on the end of the url as mentionned

 

but, if I simply go to /games/, it doesn't redirect me. It will only redirect me if there is something after the trailing slash

 

I've tried experimenting, but I just can't seem to find anything which will work both with and without that final regular expression part. Hopefully it's something simple, it's quite a nuisance

 

Thank you for your time, I hope you can bear with me

~Chris

 

Link to comment
https://forums.phpfreaks.com/topic/197172-optional-regular-expression-ending/
Share on other sites

The + asks for one or more of the characters associated with it (i.e. one or more not-forward-slash-or-dot characters). To allow none, use * instead.

Great, thanks!

That worked really well, except that it wouldn't let me access the page without the slash after 'games'.

 

This is what I've finally got:

 

RewriteRule ^games([/]*)([^/\.]*)/?$ /view_media.php?type=1$2 [L]

 

It works, hopefully it's right:

The first set of characters is just to say that the trailing slash is optional, whilst the second (also optional) set is as intended, the parameters. I've used $2 at the end so that it ONLY adds the 2nd set on the end, without the slash.

 

Thanks for your help :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.