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!!
Use basename with parse_url:
To do that you can use
explode
on yourREQUEST_URI
.I've made some simple function:I used this:
Thnx to: https://stackoverflow.com/a/1361752/4189000
If you don't mind a query string being included when present, then just use
basename
. You don't need to useparse_url
as well.When the
$url
variable is generated from user input or from$_SERVER['REQUEST_URI']
; before usingecho
usehtmlspecialchars
orhtmlentities
, otherwise users could addhtml
tags or runJavaScript
on the webpage.You can use
explode
but you need to use/
as delimiter:Note that
$_SERVER['REQUEST_URI']
can contain the query string if the current URI has one. In that case you should useparse_url
before to only get the path:And to take trailing slashes into account, you can use
rtrim
to remove them before splitting it into its segments usingexplode
. So:use preg*
this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables. And this is good practice, IMHO