Remove an item from a comma-separated string [duplicate]

情到浓时终转凉″ 提交于 2020-05-23 12:38:07

问题


Let's say I have a string:

cat,mouse,dog,horse

Is there a regex or a function that will work as follows?

    1)"cat"       return string ->"mouse,dog,horse"
    2)"mouse"     return string ->"cat,dog,horse"
    3)"dog"       return string ->"cat,mouse,horse"
    4)"horse"     return string ->"cat,mouse,dog"

I need to eliminate the selected item from the string and return the remaining parts of the string.


回答1:


You mean a function that removes a certain element? Try this:

function removeFromString($str, $item) {
    $parts = explode(',', $str);

    while(($i = array_search($item, $parts)) !== false) {
        unset($parts[$i]);
    }

    return implode(',', $parts);
}

Demo




回答2:


It's as simple as exploding the string (str_getcsv) and then removing the searched term. If you have an array, then array_diff makes it very simple:

 return array_diff(str_getcsv($list), array($search));



回答3:


Working demo.

This converts both string inputs to arrays, using explode() for the list. Then you just do array_diff() to output what's in the second array but not the first. Finally we implode() everything back into CSV format.

$input = 'cat';
$list = 'cat,mouse,dog,horse';

$array1 = Array($input);
$array2 = explode(',', $list);
$array3 = array_diff($array2, $array1);

$output = implode(',', $array3);


来源:https://stackoverflow.com/questions/8676605/remove-an-item-from-a-comma-separated-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!