2009-09-01 21 views
83

我想在最後得到的字符/在URL像http://www.vimeo.com/1234567獲取字符/ url中

我該怎麼做用PHP?

+0

您可能會發現['S($ STR) - > afterLast( '/')'](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str .php#L445)很有幫助,在[這個獨立的庫](https://github.com/delight-im/PHP-Str)中找到。 – caw 2016-07-27 00:20:55

回答

182

很簡單:

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

strrpos得到斜線最後一次出現的位置; substr返回該位置後的所有內容。


正如redanimalwar提到如果沒有斜槓,這並不正常工作,因爲strrpos返回false。這裏有一個更強大的版本:

$pos = strrpos($url, '/'); 
$id = $pos === false ? $url : substr($url, $pos + 1); 
+0

哦大..它的工作對我來說..謝謝 – deadman 2014-10-02 10:21:33

+1

好的和簡單的解決方案,謝謝。 – 2015-06-12 15:13:05

+0

如果根本沒有斜線,則會削減第一個字符。 – redanimalwar 2015-11-02 13:55:21

12

你可以explode基於「/」,然後返回最後一個條目:

print end(explode("/", "http://www.vimeo.com/1234567")); 

這是基於吹開弦,東西,如果你知道該字符串的模式是沒有必要的本身不會很快改變。你可以,或者,使用正則表達式在字符串的結尾找到值:

$url = "http://www.vimeo.com/1234567"; 

if (preg_match("/\d+$/", $url, $matches)) { 
    print $matches[0]; 
} 
+0

'爆炸'總是看起來像更多的開銷給我,雖然我從來沒有時間去看它有多快。 – DisgruntledGoat 2009-09-01 10:47:01

+0

它看起來爆炸()有點慢。在10k實例中,這是兩者所花費的時間。 substr()第一次:0.013657/0.045038 – Sampson 2009-09-01 10:54:44

+0

可能會變慢,但我更喜歡這裏的爆炸。特別是如果url不包含任何「/」,strrpos答案中的+1會導致混亂爆炸能夠克服。 – Noam 2014-05-15 08:28:49

1

array_pop(explode("/", "http://vimeo.com/1234567"));將返回例如URL的最後一個元素

+0

在php7中返回通知:'PHP注意:只有變量應該通過引用傳遞'。 – billynoah 2017-01-10 14:25:35

5
$str = "http://www.vimeo.com/1234567"; 
$s = explode("/",$str); 
print end($s); 
+3

我的版本,儘管最終結果與張貼的結果相同,但是如果OP願意的話,OP可以使用拆分字符串的其他項目。 – ghostdog74 2009-09-01 11:26:13

+0

這是正確的答案,因爲標題在'last'/ url後詢問 – 2017-08-26 18:26:57

9

您可以使用substrstrrchr

$url = 'http://www.vimeo.com/1234567'; 
$str = substr(strrchr($url, '/'), 1); 
echo $str;  // Output: 1234567 
+0

更多類似這樣的:ltrim(strrchr($ url,「/」),「/」); strchr返回一個字符串,而不是一個數字 – 2015-03-26 10:24:51

28
$str = basename($url); 
+1

這是否適用於網址?不是用於文件路徑的基準名稱? – 2013-04-05 18:24:31

+1

似乎工作正常,這是一個字符串函數;它不檢查路徑是否存在。 – 2016-03-24 17:06:35

-1

這裏是一個美麗的我寫的動態函數去除url或路徑的最後部分。

/** 
* remove the last directories 
* 
* @param $path the path 
* @param $level number of directories to remove 
* 
* @return string 
*/ 
private function removeLastDir($path, $level) 
{ 
    if(is_int($level) && $level > 0){ 
     $path = preg_replace('#\/[^/]*$#', '', $path); 
     return $this->removeLastDir($path, (int) $level - 1); 
    } 
    return $path; 
} 
0

兩個一襯墊 - 我懷疑第一個是快,但第二個是漂亮,不像end()array_pop(),你可以直接傳遞一個函數的結果current()而不會產生任何通知或警告,因爲它不」不要移動指針或改變數組。

$var = 'http://www.vimeo.com/1234567'; 

// VERSION 1 - one liner simmilar to DisgruntledGoat's answer above 
echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0)); 

// VERSION 2 - explode, reverse the array, get the first index. 
echo current(array_reverse(explode('/',$var)));