Welcome Guest, Not a member yet? Register   Sign In
Transform underscore to dash in segment_array URI function
#1

[eluser]kitefr[/eluser]
Hi guys !

I work with CodeIgniter for a few months now and i come to think about how to change value with underscore in an array to dash ones.

Because i wrote my own function to create menu and I'm using dash into the URL instead of underscore as method arguments.

The thing is i was using the URI function segment_array() but in take controllers and methods and arguments as the really like : with underscore because the dash ones are only for view and be pretty.

so i create my own function to take segment array with dash instead of underscore and i wanted to give to people who maybe need it !

So i made the MY_Uri.php library :

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Uri extends CI_URI {
    
    var $dash_segments = array();
    
    function MY_Uri()
    {
        parent::CI_URI();
    }

    function dash_segment_array()
    {
        $CI =& get_instance();
        $uri_array = $CI->uri->segment_array();
        
        foreach($uri_array as $key => $value) :
            if(preg_match_all('/[_]+/', $value ,$matches, PREG_SET_ORDER)) {
                $new_uriarray[$key] = preg_replace('/[_]+/', '-', $value);
            } else {
                $new_uriarray[$key] = $value;
            }
        endforeach;
        
        if(!empty($new_uriarray)) {
            return $new_uriarray;
        }
    }
}

Put it into your library's application folder and use the function like the other uri function !

Code:
ex : $this->uri->dash_segment_array();

So now the array will be like that :
Code:
Array
{
   [1] => [series]
   [2] => [view]
   [3] => [infos]
   [4] => [name-of-your-serie]
}

Instead of like that :
Code:
Array
{
   [1] => [series]
   [2] => [view]
   [3] => [infos]
   [4] => [name_of_your_serie]
}

I'm not a programmer and I'm learning by myself by passion so if someone can make a better code and a cleaner one, I will be interested !

Thank you ^^
#2

[eluser]InsiteFX[/eluser]
str_replace is faster then preg_replace

You only need to use preg_replace if using regx

InsiteFX
#3

[eluser]tonanbarbarian[/eluser]
have a look at the array_walk function
http://au2.php.net/manual/en/function.array-walk.php
#4

[eluser]kitefr[/eluser]
Thanks i change to str_replace instead Smile

for array_walk i'm still trying to understand how to use it... ^^;




Theme © iAndrew 2016 - Forum software by © MyBB