Eiad Samman
Eiad Samman

Reputation: 407

Regex matching url with a specific words

Using apache rewrite I want to redirect urls to a file with a specific patterns

images/gallery/photos/album/thumb/image.jpg
images/gallery/photos/album/view/image.jpg
images/gallery/photos/album/image.jpg

Using regex i want to match (photos/album/) as a part Returns (thumb|view) if provided And last returns the last part of the url (image.jpg)

My final approach is

^images/gallery/(.*/)*((view|thumb)/)+(.*)$
Array
(
    [1] => photos/album/
    [2] => thumb/
    [3] => image.jpg
)

Which works perfect if ONLY (view|thumb) is provided, but if replaced + with ? the regex returns images/gallery/thumb/ without passing (thumb) as a part

^images/gallery/(.*/)*((view|thumb)/)?(.*)$
Array
(
    [1] => photos/fresh-water-fish/thumb/
    [2] => 
    [3] => Plant_Aquarium.jpg
)

What is the best solution to get (view|thumb) if provided

Upvotes: 1

Views: 1593

Answers (3)

deathpote
deathpote

Reputation: 250

^images/gallery/(\w+/\w+)/?(view|thumb)?/?([^/]*)$

this one will match :

$1 : "photo/album"

$2 : "view", "thumb" or ""

$3 : "image.jpg"

Upvotes: 1

Pęgaz
Pęgaz

Reputation: 46

Try using instead of
images/gallery/(.*/)*((view|thumb)/)?(.*)$
this one:
images/gallery/(.*/)*((view|thumb)?/)(.*)$

I'm not shure why greedy regex '?' don't work on groups, but it works fine on specific value ('[1,2]', '.', '(text|text2)', etc.)

Upvotes: 0

karthik manchala
karthik manchala

Reputation: 13640

You can use the following:

^images/gallery/((?:[^./]*/)*?)((view|thumb)/)?([^/]*)$

See DEMO

Upvotes: 3

Related Questions