2

I need help with a regex redirect.

I have a working regex

'^page\.php\?t=(\d+)$' => 'page/t-$1/'

to redirect

/page.php?t=123 > /page/t-123/

I need regex to redirect

/page.php?t=123/dynamic-text-123/ > /page/t-123/dynamic-text-123/
3
  • 1
    Maybe ^page\.php\?t=(\d+)\$u=\/(?:\w+-)+\d+$ Commented Mar 4, 2018 at 9:29
  • 1
    Try ^page\.php\?t=(.*)$ Commented Mar 4, 2018 at 9:37
  • This worked, Thank you '^page\.php\?t=(.*)$' => 'page/t-$1/' Commented Mar 4, 2018 at 9:53

1 Answer 1

1

You effectively only need to remove the .php?t= portion.

Since it seems that you are comfortable hardcoding the leading page component, you only need to match the trailing t value with a lazy wildcard (.*?) and exclude the optional trailing / then append that captured value to page/t-, then apend a slash at the end like so:

 '^page\.php\?t=(.*?)/?$' => 'page/t-$1/'

I am making the trailing / match optional, since it is not always there yet it seems you want the / in the replacement no matter what.

Sign up to request clarification or add additional context in comments.

4 Comments

I have a question just for my understanding. Why make the ending forward slash optional /? when the greedy .* already matches it?
Because in the first sample input there is no / at the end, but in the second sample input, it is present at the end. The desired replacement always wants the / at the end, so I am hardcoding it into the replacement and omitting it from the capture group.
Wouldn't the optional / at the end be in the captured group with the greedy .*?
My mistake, I should have tested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.