Delete Trailing Commas In PHP

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.

$values = array('one', 'two', 'three', 'four', 'five');
$string = '';
 
foreach ( $values as $val ) {
    $string .= '"'.$val.'", ';
}
 
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.

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

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:

$string = '"one", , ,  , , , ,,';
echo $string;
$string = deleteTrailingCommas($string);
echo $string;

This prints out the following:

"one", , ,  , , , ,,
"one"

Comments

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

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
16 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.