URI 類別
URI 類別提供函數,它幫助您解析 URI 字串資訊。假如您使用了 URI routing,也可以利用類別解析網址字串所設定的 re-routed 區段
注意:URI 類別會被系統自動初始化,所以不必手動啟動它。
$this->uri->segment(n)
允許你檢索特定的區段部份。n 是您想檢索的特定區段,區段是由左到右順序排列,底下簡單來說,假設您的 URL 網址如下:
http://example.com/index.php/news/local/metro/crime_is_up
全部的區段分別是:
- news
- local
- metro
- crime_is_up
假如指定區段不存在,此函數將會回傳 FALSE (boolean)。如果該區段不存在,您也可以設定第二個參數來代表。底下例子代表說,當發生區段不存在時,就會回傳預設值 0:
$product_id = $this->uri->segment(3, 0);
它可以有效的避免出現以下的程式碼:
if ($this->uri->segment(3) === FALSE)
{
$product_id = 0;
}
else
{
$product_id = $this->uri->segment(3);
}
$this->uri->rsegment(n)
這個函數與上個函數相同,除此之外當你使用 URI Routing 的事件時,你還可以透過此函數取得你所指定的 re-routed 區段
$this->uri->slash_segment(n)
這個函數幾乎與 $this->uri->segment() 函數相同,除此之外它還有第二個參數來讓你決定加入斜線的地方,如以下範例所示:
$this->uri->slash_segment(3);
$this->uri->slash_segment(3, 'leading');
$this->uri->slash_segment(3, 'both');
回傳:
- segment/
- /segment
- /segment/
$this->uri->slash_rsegment(n)
這個函數與上個函數相同,除此之外當你使用 URI Routing 時,可以讓你從 re-routed URI 中指定區段來增加斜線
$this->uri->uri_to_assoc(n)
這個函數讓你將 URI 區段轉換成關聯式陣列,範例如下:
index.php/user/search/name/joe/location/UK/gender/male
使用這個函數可以讓你將 URI 轉換成如下方的關聯式陣列:
[array]
(
'name' => 'joe'
'location' => 'UK'
'gender' => 'male'
)
第一個參數可以讓你決定位移量,預設位移量是 3 ,因為以一般來說第 1 參數與第 2 參數通常都是控制器與函數:
$array = $this->uri->uri_to_assoc(3);
echo $array['name'];
第二個參數可以讓你設定預設的陣列索引值,因此即使 URI 沒有包含到個索引,還是有索引值可以回傳:
$default = array('name', 'gender', 'location', 'type', 'sort');
$array = $this->uri->uri_to_assoc(3, $default);
假如 URI 的內容中沒有包含你所設定的索引預設值,陣列依舊會把這個索引加入,並且設定值為 FALSE
$this->uri->ruri_to_assoc(n)
這個函數與上個函數相同,除此之外當你使用 URI Routing 時,它可以讓你從 re-routed URI 中建立一個關聯式陣列
$this->uri->assoc_to_uri()
建立一個關連式陣列來作為輸端並且產生 URI 字串的格式
$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
$str = $this->uri->assoc_to_uri($array);
// Produces: product/shoes/size/large/color/red
$this->uri->uri_string()
回傳完整的 URI 字串,假設你的網址字串為:
http://example.com/index.php/news/local/345
此函數將回傳:
news/local/345
$this->uri->ruri_string()
這個函數與上個函數相同,除此之外當你使用 URI Routing 時,它將回傳 re-routed URI
$this->uri->total_segments()
回傳區段個數
$this->uri->total_rsegments()
這個函數與上個函數相同,除此之外當你使用 URI Routing 時,它將從 re-routed URI 回傳區段個數
$this->uri->segment_array()
回傳一個陣列並且包含 URI 區段:
$segs = $this->uri->segment_array();
foreach ($segs as $segment)
{
echo $segment;
echo '<br />';
}
$this->uri->rsegment_array()
這個函數與上個函數相同,除此之外當你使用 URI Routing 時,它將從 re-routed URI 回傳一個陣列並且包含 URI 區段