Remove item from comma separated string

Let's say I have a line:

cat,mouse,dog,horse 

Is there a regular expression or 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 remove the selected item from the string and return the remaining parts of the string.

+4
source share
3 answers

Do you mean a function that removes a specific element? Try the following:

 function removeFromString($str, $item) { $parts = explode(',', $str); while(($i = array_search($item, $parts)) !== false) { unset($parts[$i]); } return implode(',', $parts); } 

Demo

+14
source

It is as simple as blowing up a string ( str_getcsv ) and then deleting the search term. If you have an array, then array_diff makes it very simple:

  return array_diff(str_getcsv($list), array($search)); 
+8
source

Working demonstration .

This converts both string inputs to arrays using explode() for a list. Then you just do array_diff() to output what is in the second array, but not in the first. Finally we implode() will all return to CSV format.

 $input = 'cat'; $list = 'cat,mouse,dog,horse'; $array1 = Array($input); $array2 = explode(',', $list); $array3 = array_diff($array2, $array1); $output = implode(',', $array3); 
+3
source

Source: https://habr.com/ru/post/1388554/


All Articles