URI 类

URI类提供了帮助你分割URI字符串的函数集合。如果你使用URI路由功能,那么你就可以通过分段来重新分发地址栏信息。

注意: URI类会被系统自动初始化,不必手动启用该功能。

$this->uri->segment(n)

它允许你重新分割一个详细的URI分段。 n 为你想要得到的段数。分割数按照从左至右的顺序编排。 例如,如果你完整的URL的地址如下:

  1. http://example.com/index.php/news/local/metro/crime_is_up
每个URI分段的数字编号为: - news - local - metro - crime_is_up 默认情况下URI没有分段那么该函数返回 FALSE(布尔值)。如果分段信息丢失,Segment函数还有第二个参数用来设置你的默认值。例如,这样设置后,当发生错误时,函数就会返回数字“0”。
  1. $product_id = $this->uri->segment(3, 0);
如果没有该参数你的代码必须得像下面这样写:
  1. if ($this->uri->segment(3) === FALSE)
  2. {
  3. $product_id = 0;
  4. }
  5. else
  6. {
  7. $product_id = $this->uri->segment(3);
  8. }

$this->uri->rsegment(n)

这个函数和上面的函数基本功能一样,不同点在于它允许你在开启CodeIgniter的URI路由功能时进行详细分割并重新分发URI信息

$this->uri->slash_segment(n)

这个函数几乎和$this->uri->segment()一模一样,不过它可以通过第二个参数(" ","leading","both")给返回的URI参数加上“/”线,如果不使用该参数,就会在后面增加斜画线。例如:

  1. $this->uri->slash_segment(3);
  2. $this->uri->slash_segment(3, 'leading');
  3. $this->uri->slash_segment(3, 'both');
返回: - segment/ - /segment - /segment/ ## $this->uri->slash_rsegment(n) 这个函数功能同上面的函数,不同点在于它允许你在开启CodeIgniter的[URI路由]($c7e9366e5e8c497a.md)功能时进行详细分割并重新分发URI信息并可以增加斜线“/”。 ## $this->uri->uri_to_assoc(n) 你可以使用这个函数把每个分段信息以"标识字"=>"具体值"的形式存放在一个联合数组Array()里。注意这个URI:
  1. index.php/user/search/name/joe/location/UK/gender/male
使用这个函数你可以把URI以如下原型翻转到联合数组中:
  1. [array]
  2. (
  3. 'name' => 'joe'
  4. 'location' => 'UK'
  5. 'gender' => 'male'
  6. )
函数第一个参数可以设置偏移量,默认设置为3,因为一般情况下你的URI包含 控制器名 / 函数名 作为第一个和第二个分段。例如:
  1. $array = $this->uri->uri_to_assoc(3);
  2. echo $array['name'];
第二个参数可以用来设置"标识字",这样返回的数组总会包含索引里的标识字,甚至在丢失URI的情况下也是如此。例如:
  1. $default = array('name', 'gender', 'location', 'type', 'sort');
  2. $array = $this->uri->uri_to_assoc(3, $default);
如果URI不包含对应你所给标识字的具体值时,该索引的值会被设置为"FALSE"。 最后,如果相应的具体值找不到给定的标识字时(若URI段数为是一个单数时)具体值也会被设置为"FALSE"(布尔值) ## $this->uri->ruri_to_assoc(n) 这个函数和上面的函数基本功能一样,不同点在于它允许你在开启CodeIgniter的[URI路由]($c7e9366e5e8c497a.md)功能时把URI信息分割并翻转到联合数组中去。 ## $this->uri->assoc_to_uri() 这个函数的功能和uri_to_assoc的功能找相反,它把数组里的信息翻转成URI地址,例如:
  1. $array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
  2. $str = $this->uri->assoc_to_uri($array);
  3. // 输出: product/shoes/size/large/color/red

$this->uri->uri_string()

返回一个包含完整URI信息的字符串。例如,假设以下为你的完整URL:

  1. http://example.com/index.php/news/local/345
函数将返回如下字符串:
  1. news/local/345

$this->uri->ruri_string()

这个函数和上面的函数基本功能一样,不同点在于它允许你在开启CodeIgniter的URI路由功能时把URI转换成对应的字符串。

$this->uri->total_segments()

返回总的URI的段数

$this->uri->total_rsegments()

这个函数和上面的函数基本功能一样,不同点在于它允许你在开启CodeIgniter的URI路由功能时返回URI的段数。

$this->uri->segment_array()

返回一个包含URI分段的数组。例如:

  1. $segs = $this->uri->segment_array();
  2. foreach ($segs as $segment)
  3. {
  4. echo $segment;
  5. echo '<br />';
  6. }

$this->uri->rsegment_array()

这个函数和上面的函数基本功能一样,不同点在于它允许你在开启 CodeIgniter 的 URI 路由功能时返回 URI 的数组。

翻译贡献者:Hex, lomatus