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