4

Say I have the following URL values:

http://website.com/tagged/news/
http://website.com/tagged/news
http://www.website.com/tagged/news/
http://www.website.com/tagged/news

I'd like to have a PHP function to get news in this example. So I want the value after the last slash if it isn't blank and if that value is blank, then I'd like to get the value before that slash.

I found this post: Get last word from URL after a slash in PHP

But I'd like to be really sure just in case someone types a slash at the end of the URL.

j08691
  • 204,283
  • 31
  • 260
  • 272
user1048676
  • 9,756
  • 26
  • 83
  • 120

4 Answers4

16

As easy as:

substr(strrchr(rtrim($url, '/'), '/'), 1)
zerkms
  • 249,484
  • 69
  • 436
  • 539
4

You can also use basename($url)

Rob
  • 12,659
  • 4
  • 39
  • 56
1

A little more verbose, but something like this should work:

$url = ... //your url
//trim slashes off the end to make sure url doesn't end with slash
$results = explode('/', trim($url,'/'));
if(count($results) > 0){
    //get the last record
    $last = $results[count($results) - 1];
}
Crwydryn
  • 840
  • 6
  • 13
0

You can try preg_match()

See http://php.net/manual/en/function.preg-match.php and http://www.regular-expressions.info/

Oussama Jilal
  • 7,669
  • 2
  • 30
  • 53