1

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.

2 Answers 2

1

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

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

1 Comment

@Jerry: if you check the question you'll see that it's fine
0

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',
)

Comments

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.