CodeIgniter Forums

Full Version: How to retrieve URI segments in a specified RANGE (Code provided)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Genki1[/eluser]
Have you ever wanted to retrieve URI segments in a RANGE, rather than ALL segments or a SINGLE segment?

Here is the answer to your prayers:

Code:
/**
* @author  Steve Rumberg,  Steve [email protected] SteveRumberg.com
* @copyright Copyright (c) 2012 Steve Rumberg
* @license  free for any use, personal or commercial. Attribution appreciated :-)
*
* Retrieve a specified range of segments from the URI string
*
* This function returns URI segments starting at the specified location and
* continuing for X number of segments, if specified.
*
* For example, if this is your URL:
*   http://www.StatementConverter.com/index.php/controller/function/id/and/other/elements/here
*
* A. Retrieve all the segments starting with segment three
*     segment_range_array(3);
*       Result:  array([0] => 'id', [1] => 'and', [2] => 'other', [3] => 'elements', [4] => 'here')
*     segment_range_string(3);
*       Result:  '/id/and/other/elements/here'
*
* B. Retrieve segments three and four:
*     segment_range_array(3, 2);
*       Result:  array([0] => 'id', [1] => 'and')
*     segment_range_string(3, 2);
*       Result:  '/id/and'
*
* C. Retrieve segments four through six:
*     segment_range_array(4, 3);
*       Result:  array([0] => 'and', [1] => 'other', [2] => 'elements')
*     segment_range_string(4, 3);
*       Result:  '/and/other/elements'
*
* D. Retrieve segments four through six, keeping the PHP array keys:
*     segment_range_array(4, 3, TRUE);
*       Result:  array([4] => 'and', [5] => 'other', [6] => 'elements')
*     segment_range_string(4, 3);
*       Result:  '/and/other/elements'
*
* Testing/Viewing the results:
*   echo '<p>' . print_r($this->segment_range_array(4, 3, TRUE));
*   echo '<p>' . $this->segment_range_string(4, 3);
*
* @access public
* @param integer the starting segment number (the CI position number, not the PHP position number)
* @param array the number of sequential segments to return
* @param boolean whether or not to retain the original PHP array keys
* @return array or string
*/

public function segment_range_array($first = 1, $qty = NULL, $preserve_keys = FALSE)
{
// returns an array
return array_slice($this->uri->segment_array(), $first - 1, $qty, $preserve_keys);
}

public function segment_range_string($first = 1, $qty = NULL)
{
// returns a string
return DIRECTORY_SEPARATOR . implode('/', array_slice($this->uri->segment_array(), $first - 1, $qty));
}