Pregunta

Me gustaría obtener el último segmento de ruta en una URL:

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

Por ejemplo, en estas dos URL, quiero obtener el segmento de ruta:'wce' y 'dut2a'.

Intenté usar $_SERVER['REQUEST_URI'], pero obtengo la ruta URL completa.

¿Fue útil?

Solución

Probar:

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

Suponiendo $tokens tiene al menos 2 elementos.

Otros consejos

Prueba esto:

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

También he probado con algunas direcciones URL de los comentarios. Voy a tener que asumir que todos los caminos terminan con una barra, porque no puedo identificar si / bob es un directorio o un archivo. Esto asume que es un archivo a menos que tenga una barra al final también.

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

es 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 devolverá el componente de nombre final de la ruta
  • dirname devolverá la ruta del directorio principal

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

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

Prueba esto:

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

Otra solución:

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

1: conseguir la última posición de barra 2: obtener la subcadena entre la última barra y el final de cadena

Mira aquí: PRUEBA

Si desea procesar una URL absoluta, entonces usted puede utilizar parse_url() (no funciona con relativa URLs).

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

ejemplo de código completo aquí: http://codepad.org/klqk5o29

utilizar explotar función

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

escribí a mí mismo un poco de función para obtener la última dir / carpeta de un URL. Sólo funciona con direcciones URL reales / existentes, no los teóricos. En mi caso, que siempre fue el caso, por lo ...

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
}

A mí me funciona! ¡Disfrutar! Y felicitaciones a las respuestas anteriores !!!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top