1st August 2008 - 3 minutes read time
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.