我想获取网址中最后一个斜杠后面的字符,例如http://www.vimeo.com/1234567
我该如何用php实现?
$str = basename($url)
没有得到更多的赞,对我来说完全正常。 - redanimalwar请查看basename()。它应该像这样工作:
$string = basename($url);
print end( explode( "/", "http://www.vimeo.com/1234567" ) );
$url = "http://www.vimeo.com/1234567";
if ( preg_match( "/\d+$/", $url, $matches ) ) {
print $matches[0];
}
$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);
array_pop(explode("/", "http://vimeo.com/1234567"));
将返回示例 URL 的最后一个元素
PHP Notice: Only variables should be passed by reference
。 - But those new buttons though..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)));
end()
这种方式会抛出一个提示。根据文档:“你必须传递一个真正的变量而不是返回数组的函数,因为只有实际变量可以通过引用传递”。 - But those new buttons though..这是我写的一个漂亮的动态函数,用于删除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;
}
s($str)->afterLast('/')
很有用,这是在这个独立库中找到的。 - caw