Oriol del Rio
Oriol del Rio

Reputation: 709

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

I have the following URIs:

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.

Upvotes: 1

Views: 79

Answers (2)

mickmackusa
mickmackusa

Reputation: 47874

Assuming no empty directory names in your path, you can use repeated subpatterns to match an optional slash followed by one or more non-question mark, non-slash characters. After consuming these allowed characters, use \K to forget the full string match, then match any remaining characters and replace them with an empty string.

Code: (Demo)

$tests = [
    'controller/method/arg1/arg2',
    'controller/method/arg1/arg2/',
    'controller/method/arg1/arg2?param=1&param=2',
    'controller/method/arg1/arg2/?param=1&param=2',
    '/controller/method/arg1/arg2',
    '/controller/method/arg1/arg2/',
    '/controller/method/arg1/arg2?param=1&param=2',
    '/controller/method/arg1/arg2/?param=1&param=2',
];

var_export(
    preg_replace('#(?:/?[^?/]+)+\K.*#', '', $tests)
);

Output:

array (
  0 => 'controller/method/arg1/arg2',
  1 => 'controller/method/arg1/arg2',
  2 => 'controller/method/arg1/arg2',
  3 => 'controller/method/arg1/arg2',
  4 => '/controller/method/arg1/arg2',
  5 => '/controller/method/arg1/arg2',
  6 => '/controller/method/arg1/arg2',
  7 => '/controller/method/arg1/arg2',
)

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 180897

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

Upvotes: 1

Related Questions