I'm sure you guys have dealt with this before when generating a list using a loop. Let's say I have: $var = "one, two, three, four, five, "; and $var2 = "one , "; What would be the easiest way to remove the commas only from the end? So that: $var = "one, two, three, four, five "; and $var2 = "one ";
<?php /************************** * Remove Ending Comma *************************** * Written by Joel Larson (Coded Caffeine) * http://thejoellarson.com/ * Date: 23.12.09 * * Removes the comma at the end of a string, if present. **************************/ # Sample String. $string = 'This is a test string with a comma,'; /** * remove_end_comma() * PARAM: $input (The string to use) * RETURNS: -Nothing- * * Takes the $input variable (in this case, $string) and overwrites it. */ function remove_end_comma(&$input) { # Set the total length of the input. $length = strlen(trim($input)); # If the total length - 1 has a comma, then... if( strpos($input, ',', --$length) !== FALSE ) # Remove the comma and overwrite the input. $input = substr($input, 0, -1); } # Call the function. remove_end_comma($string); # $string no longer has a comma at the end. echo $string; PHP: If you want more explanations, feel free to ask.
Well the idea of the function I wrote is: Check if the comma is there If it is, remove it. If it's not, leave it alone. I tend to over-think, but it's not a bad thing.