Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last word from URL after a slash in PHP

Tags:

url

php

get

I need to get the very last word from an URL. So for example I have the following URL:

http://www.mydomainname.com/m/groups/view/test

I need to get with PHP only "test", nothing else. I tried to use something like this:

$words = explode(' ', $_SERVER['REQUEST_URI']);
$showword = trim($words[count($words) - 1], '/');
echo $showword;

It does not work for me. Can you help me please?

Thank you so much!!

like image 631
DiegoP. Avatar asked May 07 '11 12:05

DiegoP.


3 Answers

Use basename with parse_url:

echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
like image 105
sanjary Avatar answered Sep 26 '22 08:09

sanjary


by using regex:

preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test
like image 34
fardjad Avatar answered Sep 22 '22 08:09

fardjad


I used this:

$lastWord = substr($url, strrpos($url, '/') + 1);

Thnx to: https://stackoverflow.com/a/1361752/4189000

like image 25
Wouter den Ouden Avatar answered Sep 24 '22 08:09

Wouter den Ouden