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:

  • Wrapping Text using PHP
  • PHP 5.5 beta 4 is now available
  • Swapping Array Keys and Values
  • PHP Security
  • Working with Image Metadata in PHP
  • Converting Between Relative and Absolute File Path
  • Parsing File Paths with PHP
  • How to remove HTML Comments with PHP?
  • How to access .htaccess values?
  • Dealing With Common PHP Errors
  • Interview Questions and Answers for Freshers
  • Display numbers with ordinal suffix using PHP
  • Function to set COLLATION on database fields of Mysql
  • Read and write to remote files using PHP
  • Sharing PHP SESSION Variables between Multiple Subdomains
  • PHP 5.5.0 Alpha4 Development Preview Released
  • Check a string starts with http using PHP
  • Cross-Site Scripting Attacks (XSS)
  • PHP 5.4.11 and PHP 5.3.21 released!
  • PHP Memory Leak Issue
  •  

     

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