質問

私の最後のパスセグメントの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でそれをテストしてみました。 /ボブは、ディレクトリやファイルであれば、私は識別できないので、私は、すべてのパスがスラッシュで終わることを想定する必要がありますするつもりです。これは、あまりにも最後のスラッシュを持っていない限り、それがファイルであると想定されます。

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の最後のディレクトリ/フォルダを取得するために少し機能を書きました。これは、唯一の真/既存の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
}

私のための作品!楽しい!そして、前回の回答に賛辞!!!

scroll top