2

I'm trying to detect the URI with a possibility of there being get params etc. I just need to get the /val1/val2 regardless if there is any url get params etc. how can I do this in php?

Thanks

$regex = '/^\/index.php?(.*)?\?+$/';

// Here are some example URLS
site.com/val1/val2
site.com/index.php/val1/val2
site.com/index.php/val1/val2?get1=val1&get2=val2

I want to be able to group the (/val1/val2) no matter what is on the left or right of the uri

0

2 Answers 2

2

You may use

(?:/[^/?#]+){2}(?=[?#]|$)

See the regex demo

Details

  • (?:/[^/?#]+){2} - two repetitions of / and then 1+ chars other than /, ? and #
  • (?=[?#]|$) - a positive lookahead that matches a location immediately followed with ?, # or end of string.

Here is the regex graph:

enter image description here

PHP code:

$re = '~(?:/[^/?#]+){2}(?=[?#]|$)~';
$str = 'site.com/val1/val2';
if (preg_match($re, $str, $match)) {
   print_r($match[0]);
} // => /val1/val2
Sign up to request clarification or add additional context in comments.

5 Comments

just a little bit of escaping and it works: (?:\/[^\/?#]+){2}(?=[?#]|$). Just a question. Would you be able to explain it a little how it works. particularly the "?:" thanks
@TheMan68 No need to escape /, I am using ~ as a regex delimiter. You may see that no escaping is necessary here. If you handle the strings individually you may even replace (?=[?#]|$) with (?![^?#]) for better performance.
Just a side note, I find those regex diagrams to offer little help in what the pattern is actually doing. I never include them in my answers.
@TimBiegeleisen I think they are perfect for short patterns.
In all honesty I love regex and fairly handy with it but no where near your understanding unfortunately. Your above explanation doesn't help me much lol as I'm also not good at understanding the chart explanations, but thanks anyway. I'm just waiting for the site to let me mark your answer as the answer
1

We can first try splitting the string on ?, to remove the query string, if it exists. Then, split by / path separator and access the last two paths:

$url = "site.com/index.php/val1/val2?get1=val1&get2=val2";
$url = explode('?', $url)[0];
$paths = explode('/', $url);

echo "second to last element: " . $paths[count($paths)-2] . "\n";
echo "last element: " . $paths[count($paths)-1];

This prints:

second to last element: val1
last element: val2

This answer avoids using regex entirely, which might result in slightly better performance.

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.