-1

How do I get Last 3 parts of the url

For example , I have link like below

http://www.yoursite/one/two/three/drink.pdf

I will get the last part of the url using below code

$url = "http://www.yoursite/one/two/three/drink.pdf";
echo $end = end((explode('/', $url)));

But i need last 3 parts from the url like below

/two/three/drink.pdf

Please provide me a solution.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Sri
  • 121
  • 8
  • Strange question... if you use ``explode()`` anyway to slip the path components apart, then why can't you simply use the last three elements you get returned? – arkascha Sep 18 '18 at 05:52
  • If `http://www.yoursite/one` remains constant in your URL then you can use `echo ('http://www.yoursite/one/two/three/drink.pdf',23);` where 23 is the length of `http://www.yoursite/one` which you want to omit. – prashant bana Sep 18 '18 at 05:55
  • http://php.net/manual/en/function.parse-url.php in combination with http://php.net/manual/en/function.parse-str.php – Zeljka Sep 18 '18 at 05:58

2 Answers2

1

You could do this:

<?php

    $url = "http://www.yoursite/one/two/three/drink.pdf";
    $ex = explode('/', $url);

    $arr = array_slice($ex, -3, 3);
    $output = '/'.implode('/', $arr);
    var_dump($output);    // Outputs /two/three/drink.pdf

First, you use explode to break the url string into an array. Then use array_slice to get the last three elements of the array and finally implode to glue back the array elements using / as the glue.

Putting it all in one line would look like:

echo '/'.implode('/', array_slice(explode('/', $url), -3, 3));
Chukwuemeka Inya
  • 2,575
  • 1
  • 17
  • 23
0

Try below code

$url = "http://www.yoursite/one/two/three/drink.pdf";
$url_array = (explode('/', $url));
print_r(array_slice($url_array,-3,3));

Hope this helps.

Krishna Joshi
  • 315
  • 1
  • 7