Remove last character at the end of a string in PHP
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).
|
1 2 3 4 5 6 7 8 9 10 |
<?php $string = '1,2,3,4,5,'; $result = substr($string, 0, -1); echo $result; /* Output: 1,2,3,4,5 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $string = '1,2,3,4,5,'; $result = substr_replace($string, '', -1); echo $result; /* Output: 1,2,3,4,5 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $string = '1,2,3,4,5,,'; $c = ','; $result = rtrim($string, $c); echo $result; /* Output: 1,2,3,4,5 */ ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 |
<?php $string = '1,2,3,4,5,'; $result = preg_replace('/.$/', '', $string); echo $result; /* Output: 1,2,3,4,5 */ ?> |
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.
|
1 2 3 4 5 6 7 |
<?php $string = '1,2,3,4,5,,'; $c = ','; echo preg_replace("/{$c}$/", "", $string), PHP_EOL; // 1,2,3,4,5, echo preg_replace("/{$c}+$/", "", $string), PHP_EOL; // 1,2,3,4,5 ?> |
That’s all there is to removing the last character at the end of a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)