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.

回答1:

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"


回答2:

You can do this :

$url = 'www.somesite.com/archive/some-post-or-article/53272';
$id = substr(url, strrpos(url, '/') + 1);


回答3:

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


回答4:

<?php
$url = "www.somesite.com/archive/some-post-or-article/53272";

$last = end(explode("/",$url));

echo $last;

?>

Use this.



回答5:

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.



回答6:

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];


回答7:

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 :)



回答8:

$info = parse_url($yourUrl);
$result = '';

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

return $result;


回答9:

$url = 'www.somesite.com/archive/some-post-or-article/53272';
$parse = explode('/',$url);
$count = count($parse);
$yourValue = $parse[$count-1];

That's all.



标签: php url