Search code examples
phpregexuripreg-replacesanitization

Use regex to trim potential trailing slash and/or querystring from URI string


I have the following URIs:

  • /controller/method/arg1/arg2
  • /controller/method/arg1/arg2/ <- trailing slash
  • /controller/method/arg1/arg2?param=1&param=2 <- trailing query string

I need a regular expression to extract always /controller/method/arg1/arg2, while keeping in mind that it can end with /, ? or ? + some characters.

This:

^\/.*\??

is not working for me, as it is taking the chars before ?.

Ideally, I don't want the trailing / or ?, but if the pattern leaves them behind, I'll just trim them after the regex replacement.


Solution

  • I'm sure one can think of more fancy regex's, but as far as I can see, the simplest possible matching regex would be;

    ^[^?]*
    

    It cuts everything after ? off, and the other matches are - as you say - easily handled by trimming.

    A ReFiddle to test with