Removing trailing comas with PHP

by Josh Highland on November 2, 2009

php logo medium Removing trailing comas with PHPDealing 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.

  • digg Removing trailing comas with PHP
  • facebook Removing trailing comas with PHP
  • stumbleupon Removing trailing comas with PHP
  • twitter Removing trailing comas with PHP
  • delicious Removing trailing comas with PHP
  • reddit Removing trailing comas with PHP
  • friendfeed Removing trailing comas with PHP
  • posterous Removing trailing comas with PHP
  • tumblr Removing trailing comas with PHP

{ 1 comment… read it below or add one }

1 John Nicely December 31, 2009 at 5:02 am

Another way to do this (and sometimes better, if the list data needs to be manipulated), is to just push everything to an array, and then use implode(). Don’t know about speediness on that method, though…

Leave a Comment

Previous post:

Next post: