-1

I had previously been using basename to grab the last part of my URL however have noticed some issues if my URL contains parameters.

So if my URL is this: https://www.google.com/test-page/?utm_source=test

How would I pull test-page from this?

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

1 Answers1

0

You split it by the / delimiter, and then take the fourth item

$link = 'https://www.google.com/test-page/?utm_source=test';

$split = explode('/', $link);
if(isset($split[3]))
{
    echo $split[3];
}
Timberman
  • 647
  • 8
  • 24
  • 1
    Most of these basic tasks have already been covered on the site. Before posting an answer, do a quick search of the topic and if you find an existing solution, flag the question as duplicate. Don't get me wrong, it's good to see that you want to contribute, but the community prefers if we adhere to the site guidelines and avoid content duplication. – El_Vanja May 05 '21 at 13:41
  • Apologies, is it possible that if my URL is `https://www.google.com/test-page/test-sub-page/?utm_source=test` then it would grab `test-sub-page` - so basically amend the function to get the data before the last slash? – michaelmcgurk May 05 '21 at 13:42
  • Hey Michael, `$url = "https://www.google.com/test-page/test-sub-page/tester/?utm_source=test"; $path = parse_url($url, PHP_URL_PATH); $parts = explode('/', $path); $part = $parts[count($parts) - 2]; echo $part;` – michaelmcgurk May 05 '21 at 13:48