Delete Trailing Commas In PHP

14th April 2009

Converting an array of information into a string is easy, but when you are doing this for insertion into a database having trailing commas is going to mess up your SQL statements.

Take the following example, which takes an array of values and converts them into a string of values. This practice is quite common in PHP database manipulation.

  1. $values = array('one', 'two', 'three', 'four', 'five');
  2. $string = '';
  3.  
  4. foreach ( $values as $val ) {
  5. $string .= '"'.$val.'", ';
  6. }
  7.  
  8. echo $string; // prints "one", "two", "three", "four", "five",

Obviously we need to strip the trailing comma from the end of this string. To do this you can use the following function.

  1. function deleteTrailingCommas($str)
  2. {
  3. return trim(preg_replace("/(.*?)((,|\s)*)$/m", "$1", $str));
  4. }

This function uses a regular expression to match for one or more commas or spaces after the main bulk of text and before the end of the string and prints out the main bulk of text. The trailing commas are not returned.

Here is another example:

  1. $string = '"one", , , , , , ,,';
  2. echo $string;
  3. $string = deleteTrailingCommas($string);
  4. echo $string;

This prints out the following:

  1. "one", , , , , , ,,
  2. "one"

Comments

Permalink

I didn't know the trim() function accepted a second paramter. Thanks for pointing that out :)

Add new comment

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