This article demonstrates how to remove the last character at the end of a string in PHP.

1. Using substr() function

You can use the substr() function to extract a portion of the string as specified by the offset and length parameters. If length is negative, then that many characters will be excluded from the string’s end. To remove the last character from the end of a string, you can start at the 0’th position ($offset as 0) and exclude the last character ($length as -1).

Download  Run Code

2. Using substr_replace() function

Alternatively, you can use the substr_replace() function to replace the last character of the string with an empty string. It takes the input string, the replacement string, the offset position, and optionally the length of the portion. To match the last character of the string, you can give the offset as -1 and skip the length parameter.

Download  Run Code

3. Using rtrim() function

If you need to replace one or more instances of a specific character from the end of a string, you can use the rtrim() function. It accepts the input string and another string containing the characters you want to strip, and returns a string with those characters removed from the string’s end. In cases where the character is not specified, the whitespace characters are stripped from the end.

Download  Run Code

4. Using preg_replace() function

Finally, you can use preg_replace() function to remove the last character from the string. You can use regex .$ to remove the last character. Here, dot (.) matches any character, and dollar ($) matches the end of the string.

Download  Run Code

 
To remove some specific character (say, $c) from the string’s end, you can use the regex {$c}$. To remove one or more instances of the character $c from the end of a string, you can use the regex {$c}+$. The use of this function is not recommended as it takes regular expressions, which are extremely slow.

Download  Run Code

That’s all there is to removing the last character at the end of a string in PHP.