문제

고 싶을 얻을 마지막 경로 세그먼트에는 URL:

  • http://blabla/bla/wce/news.php
  • http://blabla/blablabla/dut2a/news.php

예를 들어,이러한 두 개의 Url 에 내가 원하는 경로를 얻 세그먼트:'wce',그리고'dut2a'.

사용하려고 했 $_SERVER['REQUEST_URI'], 하지만 내가 전체 URL 경로.

도움이 되었습니까?

해결책

노력하다:

$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];

가정합니다 $tokens 적어도 2 개의 요소가 있습니다.

다른 팁

이것을 보십시오:

function getLastPathSegment($url) {
    $path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
    $pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
    $pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash

    if (substr($path, -1) !== '/') {
        array_pop($pathTokens);
    }
    return end($pathTokens); // get the last segment
}

    echo getLastPathSegment($_SERVER['REQUEST_URI']);

나 또한 그것을 테스트와 함께 몇 가지에서 Url 을니다.야겠다고 추정하는 모든 경로는 슬래쉬로 끝내기 때문에,내가 할 수 있지 않을 경우 식별/밥은 디렉토리 또는 파일입니다.이 것이 그것이 가정 파일이 있지 않는 한,마지막 슬래쉬 too.

echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce

echo getLastPathSegment('http://server.com/bla/wce/'); // wce

echo getLastPathSegment('http://server.com/bla/wce'); // bla

쉽습니다

<?php
 echo basename(dirname($url)); // if your url/path includes a file
 echo basename($url); // if your url/path does not include a file
?>
  • basename 경로의 후행 후 이름 구성 요소를 반환합니다
  • dirname 부모 디렉토리의 경로를 반환합니다

http://php.net/manual/en/function.dirname.php

http://php.net/manual/en/function.basename.php

이 시도:

 $parts = explode('/', 'your_url_here');
 $last = end($parts);

다른 해결책 :

$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);

1 : 마지막 슬래시 포지션 가져 오기 2 : 마지막 슬래시와 문자열 끝 사이의 하위 문자열 가져 오기

이봐: 테스트

절대 URL을 처리하려면 사용할 수 있습니다. parse_url() (상대 URL에서는 작동하지 않습니다).

$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;

전체 코드 예제 : http://codepad.org/klqk5o29

사용 터지다 기능

$arr =  explode("/", $uri);

나는 URL의 마지막 Dir/폴더를 얻는 데 약간의 기능을 썼습니다. 이론적 인 URL이 아닌 실제/기존 URL과 만 작동합니다. 제 경우에는 항상 그렇습니다.

function uf_getLastDir($sUrl)
{
    $sPath = parse_url($sUrl, PHP_URL_PATH);   // parse URL and return only path component 
    $aPath = explode('/', trim($sPath, '/'));  // remove surrounding "/" and return parts into array
    end($aPath);                               // last element of array
    if (is_dir($sPath))                        // if path points to dir
        return current($aPath);                // return last element of array
    if (is_file($sPath))                       // if path points to file
        return prev($aPath);                   // return second to last element of array
    return false;                              // or return false
}

나를 위해 일합니다! 즐기다! 그리고 이전 답변에 대한 Kudos !!!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top