php – Codeigniter 快速取得網址中的部分片段

方法一
假設網址:http://localhost/web/index/article/123
我們可以使用 CI 本身的方法 $this->uri->segment(位置) ,參考官方說明。要讀取出 “article” 與 “123”,我們通常會使用 Controller 中的 function 結構
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Web extends CI_Controller { function __construct() { parent::__construct(); } public function index($type, $id) { echo $type; // 取得 article echo $id; // 取得 123 } } |
直接在 function(這裡, 這裡, 這裡……) 填入對應的變數。例如我們填入了變數 $type 與 $id ,那麼與網址的對應關係就成了
web/index/article/123
localhost/控制器名稱/方法名稱/$type/$id
但是這種方法,只方便取得單一個片段,如果想要取得『web/index/article/123』怎麼辦呢?參考方法二。
方法二
假設網址:http://localhost/web/index/article/123
CI 本身提供了指定第幾個位置的片段方法:$this->uri->segment(3) ,可參考官方網站。但是一樣只能取得單一字串,也就是說
1 2 3 4 5 6 |
$this->uri->segment(1); //web $this->uri->segment(2); //index $this->uri->segment(3); //article $this->uri->segment(4); //123 |
所以,我在這邊提供一個寫好的自訂涵式,讓你可以更快組合在一起。請記得放入你的 helpers ,例如:application/helpers/(如果你有分類路徑)/xxx_helpers.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function uri_segment($string = false) { $ci =& get_instance(); if ($string === false) { return $ci->uri->uri_string(); } $ary = explode(",", $string); foreach ($ary as $val) { $mix .= $ci->uri->slash_segment($val); } return trim($mix, "/ "); } |
在控制器中引用你的 helpser 以後,你就可以這麼使用
1 2 3 4 5 6 7 8 9 |
public function index($type, $id) { echo uri_segment(); // web/index/article/123 echo uri_segment("1"); // web echo uri_segment("1,2,3,4"); // web/index/article/123 echo uri_segment("1,4"); // web/123 } |
因為這支 function 太常用到了,所以我會直接放在全域的 helper ,才不用每次都呼叫囉!