Skip to content

Instantly share code, notes, and snippets.

@abdullahbutt
Created April 9, 2014 10:37
Show Gist options
  • Save abdullahbutt/10253010 to your computer and use it in GitHub Desktop.
Save abdullahbutt/10253010 to your computer and use it in GitHub Desktop.
get last word from url after a slash in php
get last word from url after a slash in php
preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test
OR
Use basename with parse_url:
echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
OR
You can use explode but you need to use / as delimiter:
$segments = explode('/', $_SERVER['REQUEST_URI']);
Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));
1 down vote
To do that you will need to use explode on your REQUEST_URI.I've made some simple function:
function getLast()
{
$requestUri = $_SERVER['REQUEST_URI'];
# Remove query string
$requestUri = trim(strstr($requestUri, '?', true), '/');
# Note that delimeter is '/'
$arr = explode('/', $requestUri);
$count = count($arr);
return $arr[$count - 1];
}
echo getLast();
use preg*
if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
echo $vv[1];
else
echo "Nothing here";
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment