Remove Last Character from String in PHP

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

In the code above, we first declare a string variable called $str and initialize it with the value JavaBlog is the best.

Then, we use the substr() function to extract a substring from $str starting 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() function

To 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 operation

Output

rtrim() 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

This function works like substr(), but it is designed to handle multi-byte character encodings.

Use the preg_replace() function

We 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

Use the str_split() and array_pop() function

You can use the str_split() and array_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 the array_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

That’s all about how to remove last character from String in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *