Removing trailing comas with PHP

php_logo_mediumDealing with trailing comas in lists is common problem for developers. I found the best way to handle this situation in PHP is with the following regular expression.

$string = eregi_replace(',$', '', $string);

Before: string = “2, 6, 9,”
After:
string = “2, 6, 9”

Only the trailing coma will be stripped. If no coma is found, the string simply passes through. It’s a simple and effective solution.