Saturday, March 20, 2010

Removing trailing comas with PHP

November 2, 2009 by Josh Highland  
Filed under php, tutorials

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.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • FriendFeed
  • MySpace
  • Ping.fm
  • StumbleUpon
  • Technorati
  • Tumblr
  • Twitter
  • Yahoo! Bookmarks

Comments

One Response to “Removing trailing comas with PHP”
  1. John Nicely says:

    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…

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!