Codeigniter uses a validation callback to change the presented value

I have text input where users send CSV, for example. red, blue, red, yellow

If the user sends duplicate values, for example, redas shown above, I want to remove the duplicate. I started making a callback, but I'm not sure how to complete it.

    //callback rule
    function _remove_dublicate($str) 
    {
            $val = strtolower($str); //make everything lowercase
            $colors = str_getcsv($val); //create array                          
            $result = array_unique($colors); //remove duplicates

    }

If there are duplicates, what should I do to send a new row from $resultto the database?

Below is my validation form

$this->form_validation->set_rules('colors', 'Colors', 'trim|required|xss_clean|regex_match[/^[a-z, ]+$/i]|callback__remove_dublicate');


        if ($this->form_validation->run() == FALSE) //if validation rules fail
        {           
            $this->load->view('edit/form');
        }
        else //success
        {
            $data = array (
                'colors' => $this->input->post('colors')
            );          
            $this->My_model->colors_update($data);          
        }

EDIT

based on Cabaret suggestion I added this to the operator elseto remove dublicates

$colors = str_getcsv($this->input->post('colors')); //create array
$result = array_unique($colors); //remove duplicates
$comma_separated = implode(",", $result); //add back CSV string

$data = array (
    'colors' => $comma_separated
);          

It seems to work

+3
source share
2 answers

, , "prep", (: trim, xss_clean, strtolower).

, , , return $result , , . :

//callback rule
function _remove_duplicate($str = '') 
{
    $val = strtolower($str); //make everything lowercase
    $colors = str_getcsv($val); //create array 
    // you could also use explode(',', $colors)
    // if you aren't expecting other delimiters than a comma
    // i.e. no commas within quotes                         
    $result = array_unique($colors); //remove duplicates
    $result = implode(',', $result); // back to string value
    return $result; // Return the value to alter the input
}

, , return FALSE, , , count($colors) === count($result), $result . , , , true/false .

- Form_validation ( ) , , .

"". :

, , , . , :

$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[5]|max_length[12]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|matches[passconf]|md5');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

"" , MD5 "xss_clean", .

PHP, , , , htmlspecialchars, trim, MD5 ..

. prepping , , , .

, , , , , , , , , . ( PHP, : CI, .), , Form_validation, .

, : , . , .

, .

+6

, . , . , Userguide . true false, .

, else , .

, -, , , .

+2
source

All Articles