Tuesday, October 1, 2013

How To Remove Last Comma From The End of String in PHP?

If you want to remove the comma from the end of a string, you can use various tricks. But one simple trick is to use PHP inbuilt function rtrim(). The rtrim function (and corresponding ltrim() for left trim) is very useful as you can specify a range of characters to remove.

rtrim() strips whitespace (or other characters) from the end of a string.

$string = "Hello, I, am, Anup,";
echo $string = rtrim($string, ','); //it will remove a char if the last char is a comma

//output : "Hello, I, Am, Anup";
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);

No comments:

Post a Comment