Php substr擷取網址最後

在PHP中,可以使用substr()函式來提取URL中的最後部分,也就是所謂的"路徑片段"(path segment)。下面是一個簡單的例子:

<?php
$url = 'https://example.com/path/to/somewhere';
$lastSegment = substr($url, strrpos($url, '/') + 1);
echo $lastSegment; // 輸出: somewhere
?>

在這個例子中,我們首先使用strrpos()函式來查找URL中最後一個/字元的位置。然後,我們使用substr()函式從該位置開始提取字元串,直到URL的末尾。

請注意,這個例子假設URL總是以/字元結尾,如果不是這樣,你需要檢查URL的格式,並相應地調整代碼。例如,如果URL沒有以/結尾,那麼strrpos()函式將返回false,你需要檢查這個情況。

<?php
$url = 'https://example.com/path/to/somewhere';
if (($lastSlashPos = strrpos($url, '/')) !== false) {
    $lastSegment = substr($url, $lastSlashPos + 1);
} else {
    // 處理沒有斜槓的情況
    $lastSegment = '';
}
echo $lastSegment;
?>

在上面的代碼中,我們首先檢查strrpos()函式是否返回了false,如果是,那麼我們知道URL中沒有斜槓,所以我們設定$lastSegment為空字元串。如果不是,我們就使用$lastSlashPos來提取最後的路徑片段。