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.
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.