4

假设我有以下 URL 值:

http://website.com/tagged/news/
http://website.com/tagged/news
http://www.website.com/tagged/news/
http://www.website.com/tagged/news

在这个例子中,我想要一个 PHP 函数来获取新闻。所以我想要最后一个斜杠之后的值,如果它不是空白并且如果那个值是空白的,那么我想得到那个斜杠之前的值。

我发现了这篇文章: Get last word from URL after a slash in PHP

但我想确定一下,以防万一有人在 URL 末尾键入斜杠。

4

4 回答 4

14

一样容易:

substr(strrchr(rtrim($url, '/'), '/'), 1)
于 2013-02-25T20:54:26.373 回答
4

你也可以使用basename($url)

于 2013-02-25T20:56:57.383 回答
1

有点冗长,但这样的事情应该有效:

$url = ... //your url
//trim slashes off the end to make sure url doesn't end with slash
$results = explode('/', trim($url,'/'));
if(count($results) > 0){
    //get the last record
    $last = $results[count($results) - 1];
}
于 2013-02-25T21:06:42.447 回答
0

你可以试试 preg_match()

请参阅http://php.net/manual/en/function.preg-match.phphttp://www.regular-expressions.info/

于 2013-02-25T20:55:41.380 回答