Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

replace

php

csv

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.

like image 887
dinchakpianist Avatar asked Dec 30 '11 05:12

dinchakpianist


2 Answers

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

like image 126
Ry- Avatar answered Oct 11 '22 23:10

Ry-


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));
like image 9
mario Avatar answered Oct 12 '22 00:10

mario