Pergunta

Eu gostaria de obter o último segmento de caminho em um URL:

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

Por exemplo, nesses dois URLs, quero obter o segmento de caminho: 'WCE' e 'Dut2a'.

Eu tentei usar $_SERVER['REQUEST_URI'], mas eu recebo todo o caminho da URL.

Foi útil?

Solução

Tentar:

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

Assumindo $tokens tem pelo menos 2 elementos.

Outras dicas

Experimente isso:

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']);

Também o testei com alguns URLs dos comentários. Vou ter que assumir que todos os caminhos terminam com uma barra, porque não consigo identificar se /bob é um diretório ou um arquivo. Isso assumirá que é um arquivo, a menos que tenha uma barra à direita também.

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

Isso é fácil

<?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 Retornará o componente de nomes à direita do caminho
  • dirname Vai devolver o caminho do diretório pai

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

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

Experimente isso:

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

Outra solução:

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

1: Obtendo a última posição de barra 2: Obtendo a substring entre a última barra e o final da corda

Olhe aqui: TESTE

Se você deseja processar um URL absoluto, pode usar parse_url() (Não funciona com URLs relativos).

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

Exemplo de código completo aqui: http://codepad.org/klqk5o29

usar explodir função

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

Eu me escrevi uma pequena função para obter o último diretor/pasta de um URL. Funciona apenas com URLs reais/existentes, não teóricos. No meu caso, esse sempre foi o caso, então ...

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
}

Funciona para mim! Apreciar! E parabéns às respostas anteriores !!!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top