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:

  • $string: It is mandatory parameter which specifies the string to be checked.
  • $charlist: It is an optional parameter. It specifies which characters to be removed from string.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

  • $patt: It contains string element which is used to search content and it can be a string or array of string.
  • $replace: It is mandatory parameter which specifies the string or an array with strings to replace.
  • $string: The string or an array with strings to search and replace.
  • $limit: Parameter specifies the maximum possible replacements for each pattern.
  • $count: Optional parameter. This variable will be filled with the number of replacements done.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
   
?>

chevron_right


Output:

GeeksforGeeks is a best platform


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.