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 items from the string and return the remaining parts of the string.
Also, read:
- 15+ regular expressions for PHP developers
- Convert Associative Array into XML in PHP
- Convert XML into Associative Array in PHP
- Converting an Array to JSON in PHP
- Converting JSON to Array or Object in PHP
<?php function removeItemString($str, $item) { $parts = explode(',', $str); while(($i = array_search($item, $parts)) !== false) { unset($parts[$i]); } return implode(',, $parts); }
<?php $mystring = 'cat,mouse,dog,horse'; $result_string = removeItemString($mystring, "mouse"); echo "Input String: ".$mystring; echo “Output String: ".$result_string; ?>
Input String: cat,mouse,dog,horse
Output String: cat,dog,horse
You may also like:
- Working with php.ini file Configuration
- Control Statements in PHP
- Convert Associative Array into XML in PHP
- Convert XML into Associative Array in PHP
- Using Prepared Statement with PHP & MySQL
- How to Upload File in PHP
- Converting an Array to JSON in PHP
- Converting JSON to Array or Object in PHP
- Manipulating PHP arrays: push, pop, shift, unshift
- Remove Repeated Words From String in PHP
- Converting a PHP Array to a Query String
- 15+ regular expressions for PHP developers
- 10 Most Important Directory Functions in PHP
- 10 little known but useful PHP functions
- PHP Script to Download Large Files Reliably
Thank you– just what I needed.
There’s a tiny (but fatal) error in your return implode() line, though:
return implode(‘,, $parts);
needs a close quote after the comma–
return implode(‘,’, $parts);