Clean Up A Comma Separated List In PHP

1st August 2008

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.

  1. $list= trim($list);
  2. $patterns[0] = '/\s*,\s*/';
  3. $patterns[1] = '/,{2,}/';
  4. $patterns[2] = '/,+$/';
  5. $patterns[3] = '/^,+/';
  6. $replacements[0] = ',';
  7. $replacements[1] = ',';
  8. $replacements[2] = '';
  9. $replacements[3] = '';
  10. $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

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

Adrian Gonzales (Mon, 12/06/2010 - 19:23)

Add new comment

The content of this field is kept private and will not be shown publicly.