Clean Up A Comma Separated List In PHP

Getting users to enter a list of items is a normal practice, but getting users to do it properly is sometimes a challenge in itself. Some users will put spaces in between the commas, others will not, some will even put a trailing comma at the end of the list.

Here is some code that can be used to clear up a comma separated list using some simple regular expressions. It works using the preg_replace() function, and by passing this function an array of options patterns and an array of replacements.

$list= trim($list);
$patterns[0] = '/\s*,\s*/';
$patterns[1] = '/,{2,}/';
$patterns[2] = '/,+$/';
$patterns[3] = '/^,+/';
$replacements[0] = ',';
$replacements[1] = ',';
$replacements[2] = '';
$replacements[3] = '';
$list= preg_replace($patterns, $replacements, $list);

Take the following string, entered by a user at 2 o'clock in the morning, whilst surfing the net drunk after coming home from the pub.

, ,,,item 1,,, ,, ,,, , item 2, item 3 ,item4, ,,,,, item 5,,, ,, ,, , ,

This awful string gets converted to the following neat and tidy string.

item 1,item 2,item 3,item 4,item5

The code works by first replacing any spaces before or after commas, then by replacing multiple commas with single commas. Finally the code detects any commas at the start or end of the string and removes them.

Comments

I think it performs better than the regex, but you can use a few functions wrapped around each other:

implode(",",array_filter(explode(",",trim($olist))));
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.