[英]Get the last 3 words from url path
像這樣的網址:
http:// localhost / 333 / ed / a3
我嘗試過這樣
$pattern = '/(([^ ]*)\s+([^ ]*)\s+([^ ]*))$/';
preg_match($pattern, $_SERVER['REQUEST_URI'], $matches);
$last_word = $matches[0];
我收到錯誤未定義偏移量:0
您當前的錯誤似乎正在發生,因為數組中沒有第零個匹配項。 這是因為您的模式與URL不匹配。 我看到的最大問題是,您的模式堅持要匹配URL內的某些空格,這種空格應該(永遠)不會發生。
試試這個版本:
$pattern = '/[^\/]+\/[^\/]+\/[^\/]+$/';
preg_match($pattern, "http://localhost/333/ed/a3", $matches);
$last_word = $matches[0];
print_r(preg_split("/\//", $last_word));
Array
(
[0] => 333
[1] => ed
[2] => a3
)
它一定是正則表達式嗎? 如果是這樣,我建議使用https://regexr.com
為簡單起見,我將展示如何將內置的explode函數與array slice函數一起使用。
http://php.net/manual/zh-CN/function.explode.php array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
http://php.net/manual/zh/function.array-slice.php array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] )
未經測試的示例:
$url = explode ( '\\' , $_SERVER['REQUEST_URI'] ); $last_three = array_slice ( $url, -3, 3 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.