PHP – Remove an Item From a Comma Separated String
Sometimes we need to remove specific item from comma separated string. Here is a running PHP function to remove an item from a comma-separated string. The function will remove the selected item from the string and return the remaining parts of the string.
view plaincopy to clipboardprint?
- <?php
- function removeItemString($str, $item) {
- $parts = explode(‘,’, $str);
- while(($i = array_search($item, $parts)) !== false) {
- unset($parts[$i]);
- }
- return implode(‘,’, $parts);
- }
- $mystring =‘cat,mouse,dog,horse’;
- $result_string = removeItemString($mystring, “mouse”);
- echo “Input String: ”.$mystring;
- echo “</br>”;
- echo “Output String: ”.$result_string;
- ?>
Input String: cat,mouse,dog,horse
Output String: cat,dog,horse
Follow @phpzag
