45

Example output

1. test,test,test,test,test,
2. test,test,test,,
3. test,test,,,
4. test,,,,,

I tried use implode according to my previous question but It's trim only last comma.

How to remove any last commas?

Community
  • 1
  • 1
wow
  • 7,989
  • 17
  • 53
  • 63

3 Answers3

111
rtrim('test,,,,,', ',');

See the manual.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
35

rtrim for example:

$str = 'foo,bar,blah,bleh,';
echo rtrim($str,',');

// foo,bar,blah,bleh
Kuchen
  • 476
  • 4
  • 6
8

completely different way:

$str = "1,2,3,4,";
$str = substr($str,0,strlen($str)-1);
Ricky
  • 1,587
  • 2
  • 12
  • 20
  • 10
    Old topic but should be noted. Although this would remove the last comma, it would only remove one comma. If the comma was missing it would remove the 4 in this example. – MHowey Mar 07 '13 at 18:47
  • Also very impractical, since it would remove not only the comma, but other characters too. For example, if we had the `$str = "1,2,3,4"`, it would remove `4`, causing us to end up with `$str = "1,2,3,"` – semihcosu Apr 27 '18 at 08:46
  • 2
    "Also very impractical" - that's too polite. It should be noted this "solution" is terrible and could lead to data loss. DO NOT USE. – Paul Feakins Apr 30 '18 at 14:24