Get value from URL after the last /

2019-06-14 01:21发布

I have looked around for this but can only find links and references to this been done after an anchor hashtag but I need to get the value of the URL after the last / sign.

I have seen this used like this:

www.somesite.com/archive/some-post-or-article/53272

the last bit 53272 is a reference to an affiliate ID..

Thanks in advance folks.

标签: php url
9条回答
Fickle 薄情
2楼-- · 2019-06-14 01:29

This will work!

$url = 'www.somesite.com/archive/some-post-or-article/53272';

$pieces = explode("/", $url);

$id = $pieces[count($pieces)]; //or $id = $pieces[count($pieces) - 1];
查看更多
Fickle 薄情
3楼-- · 2019-06-14 01:30

If you always have the id on the same place, and the actual link looks something like

http://www.somesite.com/archive/article-post-id/74355

$link = "http://www.somesite.com/archive/article-post-id/74355";
$string = explode('article-post-id/', $link);

$string[1]; // This is your id of the article :)

Hope it helped :)

查看更多
小情绪 Triste *
4楼-- · 2019-06-14 01:31

You can do it in one line with explode() and array_pop() :

$url = 'www.somesite.com/archive/some-post-or-article/53272';
echo array_pop(explode('/',$url)); //echoes 53272
查看更多
相关推荐>>
5楼-- · 2019-06-14 01:36
$info = parse_url($yourUrl);
$result = '';

if( !empty($info['path']) )
{
  $result = end(explode('/', $info['path']));
}

return $result;
查看更多
在下西门庆
6楼-- · 2019-06-14 01:37

I'm not an expert in PHP, but I would go for using the split function: http://php.net/manual/en/function.split.php

Use it to split a String representation of your URL with the '/' pattern, and it will return you an array of strings. You will be looking for the last element in the array.

查看更多
劫难
7楼-- · 2019-06-14 01:39

PHPs parse_url (which extracts the path from the URL) combined with basename (which returns the last part) will solve this:

var_dump(basename(parse_url('http://www.somesite.com/archive/some-post-or-article/53272',  PHP_URL_PATH)));
string(5) "53272"
查看更多
登录 后发表回答