how do i remove a comma off the end of a string?



I want to remove the comma off the end of a string. As it is now i am using

$string = substr($string,0,-1);

but that only removes the last character of the string. I am adding the string dynamically, so sometimes there is no comma at the end of the string. How can I have PHP remove the comma off the end of the string if there is one at the end of it?

10/29/2009 10:14:34 AM

Accepted Answer

$string = rtrim($string, ',');

Docs for rtrim here

1/22/2013 1:13:41 PM

This is a classic question, with two solutions. If you want to remove exactly one comma, which may or may not be there, use:

if (substr($string, -1, 1) == ',')
  $string = substr($string, 0, -1);

If you want to remove all commas from the end of a line use the simpler:

$string = rtrim($string, ',');

The rtrim function (and corresponding ltrim for left trim) is very useful as you can specify a range of characters to remove, i.e. to remove commas and trailing whitespace you would write:

$string = rtrim($string, ", \t\n");

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow