This article explains different ways to remove the last character from a string in PHP
Use the substr() function
To remove last character from String in PHP, use of the substr() function and pass a negative length value as argument.
Here is an example on how to use the substr() function to achieve the operation
Output
JavaBlog is the besIn the code above, we first declare a string variable called
$strand initialize it with the valueJavaBlog is the best.Then, we use the
substr()function to extract a substring from$strstarting from the first character (position 0) and with a length of -1.This effectively removes the last character from the string. Finally, we reassign the modified string to the $str variable.
We used
substr()function with length as -1 to remove last character from the String.substr() function returns a portion of the string, starting from a specified position and extending for a specified number of characters.
If a negative length value is used, the function will start at the end of the string and move backwards.
Use the
rtrim()functionTo remove last character from string in PHP, we can make of the
rtrim()function.Here is an example PHP script that shows how to use the
rtrim()function in such operationOutput
JavaBlog is the besrtrim() function removes whitespace or specified characters from the end of a string, and takes two arguments
- the string to be worked upon
- the character we want to remove.
Use the mb_substr() function
To remove last character from string in PHP, we can make use of the mb_substr() function.
mb_substr() function takes three arguments
- the string to be worked upon,
- the start index, and
- the end index which would be of a negative length value to state that we are starting from the end of the string.
Output
JavaBlog is the besThis function works like
substr(), but it is designed to handle multi-byte character encodings.Use the
preg_replace()functionWe can make use the
preg_replace()function with a regular expression to remove last character from string in PHP.preg_replace() function searches the string for a match to the regular expression and replaces it with a specified replacement string.
Here is an example on how to use the method to remove last character from a string.
Output
JavaBlog is the besUse the
str_split()andarray_pop()functionYou can use the
str_split()andarray_pop()function to remove last character from string in PHP.First, we convert the string to an array using the
str_split(), and then use thearray_pop()function to remove the last element from the array.This approach allows you to remove the last character even if it is not at the end of the string. Here is an example.
Output
JavaBlog is the besThat's all about how to remove last character from String in PHP.