views:

96

answers:

3

I've got a list of names separated by commas (they may contain other characters), or be empty, but generally looking like this:

NameA,NameB,NameC

I need to create a function to delete a name if its present in the list and which restores the comma separated structure.

eg: if NameA is to be deleted, I should end up with:

NameB,NameC

NOT

,NameB,NameC

Similarly for the rest.

This is what I came up with, is there a better solution?

        $pieces = explode(",", $list);

        $key=array_search($deleteuser, $pieces);
        if(FALSE !== $key)
        {
            unset($pieces[$key]);
        }

        $list = implode(",", $pieces);
+1  A: 

You could use the array_splice function to delete from the array. With offset = array_search($deleteuser, $pieces) and length = 1.

aniri
+1  A: 

That should work pretty well. You may also be interested in PHP's fgetcsv function.
Doc: http://php.net/manual/en/function.fgetcsv.php

blcArmadillo
A: 

You could also try a regular expression like this (maybe it can be optimized):

$search = 'NameB';
$list = 'NameA,NameB,NameC';
$list = preg_match('/(^' . $search . ',)|(,' . $search. ')/', '', $list);
Harmen