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:
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare string variable $myStr = "Welcome to TutorialDeep!"; //Remove First Character of string $StrRepFirst = substr($myStr, 1); //Echo resulted string echo $StrRepFirst; ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare string variable $myStr = "Welcome to TutorialDeep!"; //Remove Last Character of string $StrRepLast = substr($myStr, 0, -1); //Echo resulted string echo $StrRepLast; ?> |
Output
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.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare string variable $myStr = "Welcome to TutorialDeep!"; //Remove First and Last Character of string $StrRepLast = substr($myStr, 1, -1); //Echo resulted string echo $StrRepLast; ?> |
Output
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