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.

Example:
$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);
}

Comments

  1. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. String functions php

    ReplyDelete

Post a Comment

Popular Posts