php remove comma from end of a string

Every programmer will face a situation where a comma at the end of the string has to be removed for some purpose.

There are many ways of doing it.

Here in the article php remove comma at the end of a string, I am going to show some methods to remove comma.

Lets consider a example.

$string = “string,”;

Here we have to check if the end of the string is comma (,). If it is a comma we have to remove it else not.

Method 1 :

Using rtirm function:

echo rtrim($string,’,’);   // outputs “string”

Method 2 :

Using preg_replace function

echo preg_replace(“/,$/”, ” , $string)  // outputs “string”

Method 3 :

Using substr function

if(substr($string, -1) == ‘,’) {
echo  substr($string, 0, -1);  // outputs “string”
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *