How to remove last comma from a string in PHP?

To remove/trim the last/trailing or first/heading comma from a string, one should first confirm that the last character of the string is comma itself and nothing else. This would make the code foolproof and prevent accidental removal of characters other than comma.

A few methods are described here and listed in the order of increasing execution time (faster listed first),

$str = (substr($str,-1) == ',') ? substr($str, 0, -1) : $str;

or

$str = (substr($str,-1) == ',') ? substr_replace($str, '', -1) : $str;

or, to remove all trailing commas

$str = rtrim($str, ',');
//this removes all of the trailing commas eg 1,2,3,,,, => 1,2,3
//no need of condition check for last comma with rtrim()

or

$str = preg_replace("/,*$/", '', $str);
//RegEx engine overhead

Similarly, to remove first comma (or any other character) from a string you can use this,

$str = ($str[0] == ',') ? substr($str, 1) : $str;

or

$str = ($str[0] == ',') ? substr_replace($str, '',0,1) : $str;

or, to remove all heading commas

$str = ltrim($str, ',');
//this removes all of the trailing commas eg ,,,,,1,2,3 => 1,2,3
//no need of condition check for last comma with ltrim()

or

$str = preg_replace("/^,*/", '', $str);
//RegEx engine overhead

Now the question arises, why to use above methods when ltrim() and rtrim() are already there? The answer is to use methods which are fastest (or at-least faster than others) in our PHP programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>