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?

  1. <?php
  2. function removeItemString($str, $item) {
  3. $parts = explode(‘,’, $str);
  4. while(($i = array_search($item, $parts)) !== false) {
  5. unset($parts[$i]);
  6. }
  7. return implode(‘,’, $parts);
  8. }
  9. $mystring =‘cat,mouse,dog,horse’;
  10. $result_string = removeItemString($mystring, “mouse”);
  11. echo “Input String: “.$mystring;
  12. echo “</br>”;
  13. echo “Output String: “.$result_string;
  14. ?>

Input String: cat,mouse,dog,horse
Output String: cat,dog,horse

Laeeq

A web developer who has a love for creativity and enjoys experimenting with various techniques in both web design and development. If you would like to be kept up to date with our posts, you can follow us on Twitter, or even by subscribing to our RSS Feed.

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera