PHP Program to Remove Last Character from the String
Given a String, the task is to remove the last character from a string in PHP. This operation is common in text processing and manipulation.
Examples:
Input: str = "Hello Geeks!"
Output: Hello Geeks
Input: str = "Welcome"
Output: Welcom
These are the following approaches:
Approach 1: Using substr() Function
The substr() function in PHP can be used to return a part of a string. By specifying the start and length parameters, we can effectively remove the last character. The substr() function is used with the start parameter as 0 (beginning of the string) and the length parameter as -1 (which indicates one character less from the end). This effectively returns the string without the last character.
Example: This example shows the removal of last character from the given string by the use of the substr() function.
<?php
function removeLastChars($string) {
return substr($string, 0, -1);
}
// Driver Code
$str = "Hello Geeks!";
echo "Modified String: " . removeLastChars($str);
?>
Output
Modified String: Hello Geeks
Approach 2: Using rtrim() Function
The rtrim() function is another way to remove the last character from a string, especially if the character is a known whitespace or other specific character. The rtrim() function is used with the character to be trimmed specified as the second argument. This approach is useful when you specifically want to remove a known character from the end of the string.
Example: This example shows the removal of last character from the given string by the use of the rtrim() function.
<?php
function removeLastChars($string) {
return rtrim($string, "!");
}
// Driver Code
$str = "Hello Geeks!";
echo "Modified String: " . removeLastChars($str);
?>
Output
Modified String: Hello Geeks
Approach 3: Using String Manipulation
You can also use basic string manipulation to remove the last character. The substr_replace() function is used with the start parameter as -1 and the replacement string as an empty string. This effectively replaces the last character with an empty string, removing it.
Example: This example shows the removal of last character from the given string by using string manipulation.
<?php
function removeLastChars($string) {
return substr_replace($string, "", -1);
}
// Driver Code
$str = "Hello Geeks!";
echo "Modified String: " . removeLastChars($str);
?>
Output
Modified String: Hello Geeks