Get last word from URL after a slash in PHP

2019-01-18 10:45发布

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!!

标签: php url get
8条回答
老娘就宠你
2楼-- · 2019-01-18 11:23

Use basename with parse_url:

echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
查看更多
神经病院院长
3楼-- · 2019-01-18 11:25

To do that you can 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();
查看更多
唯我独甜
4楼-- · 2019-01-18 11:28

I used this:

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

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

查看更多
Juvenile、少年°
5楼-- · 2019-01-18 11:29

If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.

$url = 'http://www.mydomainname.com/m/groups/view/test';
$showword = basename($url);
echo htmlspecialchars($showword);

When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-18 11:35

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'], '/'));
查看更多
混吃等死
7楼-- · 2019-01-18 11:35

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

查看更多
登录 后发表回答