删除逗号分隔列表中值的最快方法

问题描述:

我有一个由逗号分隔的名称列表(它们可能包含其他字符),或者是空的,但通常看起来像这样:

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.

例如:如果要删除 NameA,我应该以:

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

NameB,NameC

不是

,NameB,NameC

其他的也一样.

这是我想出来的,有没有更好的解决方案?

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);

您可以使用 array_splice 函数从数组中删除.偏移量 = array_search($deleteuser, $pieces) 和长度 = 1.

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