Open In App

Removing occurrences of a specific character from end of a string in PHP

There is a lot of options to remove all specific characters at the end of a string. Some of them are discussed below:

Using rtrim() function: This function is an inbuilt function in PHP which removes whitespaces or other characters (if specified) from the right side of the string.



Syntax:

rtrim( $string, $charlist )

Parameters: This function accepts two parameters as mentioned above and described below:



Example: This example uses rtrim() function to remove ‘.’ from the end.




<?php
  
// Declare a variable and initialize it
$string = "GeeksforGeeks is a best platform.....";
  
// Use rtrim() function to trim
// string from right
echo rtrim($string, ".");
  
?>

Output:
GeeksforGeeks is a best platform

Using preg_replace() function: This function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.

Syntax:

preg_replace( $patt, $replace, $string, $limit, $count )

Parameters: This function accepts five parameters as mentioned above and described below:

Example 2: This example uses preg_replace() function to remove ‘.’ from the end.




<?php
  
// Declare a variable and initialize it
$string = "GeeksforGeeks is a best platform.....";
  
// Character which need to replace
$regex = "/\.+$/";
  
// Use preg_replace() function to replace 
// the character
echo preg_replace($regex, "", $string);
   
?>

Output:
GeeksforGeeks is a best platform

Article Tags :