tags:

views:

397

answers:

8

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  A: 

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

c0r0ner
This will remove multiple commas: "a,b,,," will become "a,b". Whether that's what the OP wants or not I don't know...
Greg
perfect, thank you!
zeckdude
A: 

Precede that with:

if(substr($string, -1)==",")
Kaivosukeltaja
+1  A: 
if(substr($str, -1, 1) == ',') {

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

}

http://php.net/manual/en/function.substr.php

Wbdvlpr
A: 

have a look at the rtrim function

rtrim ($string , ",");

the above line will remove a char if the last char is a comma

Anand
A: 

A simple regular expression would work

$string = preg_replace("/,$/", "", $string)
AlexWilson
Developer use regular expression to solve a problem and now he has two problems.
c0r0ner
A: 

rtrim ($string , ","); is the easiest way.

mepo
+1  A: 

i guess you're concatenating something in the loop, like

foreach($a as $b)
  $string .= $b . ',';

much better is to collect items in an array and then join it with a delimiter you need

foreach($a as $b)
  $result[] = $b;

$result = implode(',', $result);

this solves trailing and double delimiter problems that usually occur with concatenation

stereofrog
+3  A: 

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");
Ben Russell
Thank you for that detailed explanation. That clarifies things!
zeckdude