itsource

last / url 뒤의 문자

mycopycode 2023. 1. 15. 17:20
반응형

last / url 뒤의 문자

다음과 같은 URL에서 마지막/뒤의 문자를 가져오고 싶다.http://www.vimeo.com/1234567

php는 어떻게 해야 하나요?

매우 심플하게:

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

strpos는 슬래시의 마지막 위치를 가져옵니다.기판은 그 위치 뒤에 모든 것을 반환합니다.


redanimal war에서 언급되었듯이 슬래시가 없으면 이것은 올바르게 작동하지 않습니다.strrposfalse가 반환됩니다.보다 견고한 버전은 다음과 같습니다.

$pos = strrpos($url, '/');
$id = $pos === false ? $url : substr($url, $pos + 1);
from os.path import basename

$str = 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];
}

및 을 사용할 수 있습니다.

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567
$str = "http://www.vimeo.com/1234567";
$s = explode("/",$str);
print end($s);

array_pop(explode("/", "http://vimeo.com/1234567"));예제 URL의 마지막 요소를 반환합니다.

두 대의 라이너 - 첫 번째 라이너가 더 빠르지만 두 번째 라이너가 더 예쁘고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)));
Str::afterLast($url, '/');

라라벨 6 이후 라라벨에서의 도우미 방법.

여기 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;
}

언급URL : https://stackoverflow.com/questions/1361741/get-characters-after-last-in-url

반응형