How to Remove First and Last Character of String in PHP

Last Updated on May 13, 2021 by Roshan Parihar

In this tutorial, learn how to remove first and last character of string using PHP. The short answer is to use the substr() and specify the argument as given in this post.

Let’s find out with the examples given below to learn the method.

Remove First Character of String in PHP

To remove the first character of string in PHP, you have to use the substr() function. In this function, you have to pass two arguments in which the first argument is a string variable and the second is 1. You can see the example given below to get the idea:

Output

elcome to TutorialDeep!

The above example contains the output that shows the string with the first character removed.

How to Remove Last Character of String in PHP

To remove the last character of the string, you have to use substr() function with three arguments. The first argument takes the string variable, the second argument takes 0, and the third argument takes -1.

Output

Welcome to TutorialDeep

The above output shows that the last character in a string is ‘!’ and it is removed from the string.

Delete the First and Last Characters Using PHP

In addition to the above all methods, you can also delete the first and last characters of string using PHP. To delete the first and last character, you have to use the substr() function with three arguments. The first argument is a string variable, the second is 1, and the third is -1.

Output

elcome to TutorialDeep

The output contains the string with the first and last characters deleted from it.

The above all examples uses the same substr() to delete the letters from the string using PHP.

You May Also Like to Read

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.