developer tip

마지막 / 뒤에 문자를 가져옵니다

optionbox 2020. 7. 26. 12:52
반응형

마지막 / 뒤에 문자를 가져옵니다


마지막 / 다음과 같은 URL에서 문자를 얻고 싶습니다. http://www.vimeo.com/1234567

PHP로 어떻게합니까?


아주 간단하게 :

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

strrpos 는 마지막으로 발생한 슬래시의 위치를 ​​가져옵니다. substr 은 그 위치 뒤의 모든 것을 반환합니다.


redanimalwar에서 언급했듯이 슬래시가 없으면 strrposfalse를 반환 하므로 올바르게 작동하지 않습니다 . 보다 강력한 버전은 다음과 같습니다.

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

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

당신은 사용할 수 있습니다 substrstrrchr:

$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)));

다음은 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

반응형