TheMan68
TheMan68

Reputation: 1469

Php regex for detecting Url URI

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

Upvotes: 2

Views: 452

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520958

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.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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

Upvotes: 2

Related Questions