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"
Sleigh Beds at great prices.
Looking for Toddlers Bedding ?
Bulk SMS here
Bed Linen at great prices.
| Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. |
| Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. |
| Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. |
| Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. |
| Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit. |
For the first example, it would be a better idea to use the implode function.
$values = array('one', 'two', 'three', 'four', 'five');
$result = implode($values, ',');
echo $result;