PHP – Remove an Item From a Comma Separated String

December 27th, 2012 by Laeeq | No comments

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

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • How to Remove Leading & Trailing White Spaces with PHP
  • Parse HTML/Web Pages with PHP
  • Block Multiple IP Addresses Using PHP
  • How much memory do PHP variables use?
  • Manipulating PHP arrays: push, pop, shift, unshift
  •  

     

    1. No comments yet.
    1. No trackbacks yet.