簡體   English   中英

獲取 URL PHP 的最后一部分

[英]Get Last Part of URL PHP

我只是想知道如何使用 PHP 提取 URL 的最后一部分。

示例網址是:

http://domain.example/artist/song/music-videos/song-title/9393903

現在如何使用 PHP 提取最終部分?

9393903

URL 中始終存在相同數量的變量,並且 id 始終位於末尾。

最簡單的方法是使用basename()

echo basename('http://domain.example/artist/song/music-videos/song-title/9393903');

哪個會打印

9393903

當然,如果末尾有查詢字符串,它將包含在返回值中,在這種情況下接受的答案是更好的解決方案。

將其拆分並獲取最后一個元素:

$end = end(explode('/', $url));
# or:
$end = array_slice(explode('/', $url), -1)[0];

編輯:為了支持 apache-style-canonical URLs, rtrim很方便:

$end = end(explode('/', rtrim($url, '/')));
# or:
$end = array_slice(explode('/', rtrim($url, '/')), -1)[0];

另一個我認為更具可讀性的示例是( Demo ):

$path = parse_url($url, PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);

此示例還考慮到僅對 URL 的路徑起作用。


另一個編輯(多年后),規范化和簡單的 UTF-8 替代使用包括(通過 PHP 中的 PCRE 正則表達式):

<?php

use function call_user_func as f;
use UnexpectedValueException as e;

$url = 'http://example.com/artist/song/music-videos/song-title/9393903';

$result = preg_match('(([^/]*)/*$)', $url, $m)

    ? $m[1]
    : f(function() use ($url) {throw new e("pattern on '$url'");})
    ;

var_dump($result); # string(7) "9393903"

這很粗略,但展示了如何將它包裝在preg_match調用中,以通過 PCRE 正則表達式模式進行更細粒度的控制。 為了給這個裸機示例增加一些意義,它應該被包裝在它自己的函數中(這也會使別名變得多余)。 為簡潔起見,僅以這種方式呈現。

您可以使用preg_match來匹配您想要的 URL 部分。

在這種情況下,由於模式很簡單,我們正在尋找一個正斜杠( \/並且我們必須轉義它,因為正斜杠表示正則表達式模式的開始和結束),以及一個或多個數字( \d+ )在字符串的最后( $ )。 \d+周圍的括號用於捕獲我們想要的部分:即結尾。 然后我們將我們想要的結尾( $end )分配給$matches[1] (不是$matches[0] ,因為它與$url相同(即整個字符串))。

$url='http://domain.example/artist/song/music-videos/song-title/9393903';

if(preg_match("/\/(\d+)$/",$url,$matches))
{
  $end=$matches[1];
}
else
{
  //Your URL didn't match.  This may or may not be a bad thing.
}

注意:您可能希望也可能不希望向此正則表達式添加一些更復雜的功能。 例如,如果您知道您的 URL 字符串將始終http://開頭,那么正則表達式可以變為/^http:\/\/.*\/(\d+)$/ (其中.*表示零個或多個字符(不是換行符))。

如果您正在尋找可以處理任何形式的URL的強大版本,這應該很好:

<?php

$url = "http://foobar.example/foo/bar/1?baz=qux#fragment/foo";
$lastSegment = basename(parse_url($url, PHP_URL_PATH));
$id = strrchr($url,"/");
$id = substr($id,1,strlen($id));

這里是strrchr函數的描述: http ://www.php.net/manual/en/function.strrchr.php

另外的選擇:

$urlarray=explode("/",$url);
$end=$urlarray[count($urlarray)-1];

最優雅的解決方案之一是在這里Get characters after last / in url

由不滿的山羊

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

strrpos 獲取最后一次出現斜線的位置; substr 返回該位置之后的所有內容。

一個班輪: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));

獲取 URI,修剪斜線,轉換為數組,抓取最后一部分

故障安全解決方案是:

引用自https://stackoverflow.com/a/2273328/2062851

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

這將輕松完成工作以獲取所需 URL 的最后一部分

$url="http://domain.example/artist/song/music-videos/song-title/9393903";
$requred_string= substr(strrchr($url, "/"), 1);

這將在右邊的第一個“/”之后為您提供字符串。

$mylink = $_SERVER['PHP_SELF'];
$link_array = explode('/',$mylink);
echo $lastpart = end($link_array);
function getLastPathSegment($url) {
    $arr = explode('/', $url);
    return $arr[count($arr) - 1];
}

1班

$end = preg_replace( '%^(.+)/%', '', $url );

// if( ! $end ) no match.

這只是刪除最后一個斜杠之前的所有內容,包括它。

一線工作答案:

$url = "http://www.yoursite/one/two/three/drink";
echo $end = end((explode('/', $url)));

輸出:飲料

我很高興你問這個問題!

您可以使用此代碼:-

$request_uri = $_SERVER['REQUEST_URI'];
$request_uri_arr = explode('/', $request_uri);

$node_url = end($request_uri_arr);
echo $node_url;//this will print the last part of the url;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM