Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of a URL after the last slash

Tags:

php

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.

like image 352
user1048676 Avatar asked Nov 30 '22 21:11

user1048676


2 Answers

As easy as:

substr(strrchr(rtrim($url, '/'), '/'), 1)
like image 74
zerkms Avatar answered Dec 04 '22 04:12

zerkms


You can also use basename($url)

like image 41
Rob Avatar answered Dec 04 '22 04:12

Rob