In this article you will discover a very simple and effective way to remove the last character of a string with PHP . Very simple but very useful code that can get you out of a bind.
After many years of experience struggling with the PHP programming language , I decided to write about this little topic because, oddly enough, it is a resource that in my case I have had to use a lot.
In many situations I have had to read a string that needed to remove the last character.
I’m not wasting any more time. I’ll get to the point.
The function substr in PHP allow split chains in parts with many possibilities.
In the following tutorial you can see several usage examples; Split strings with PHP substr.
Knowing that the substr function can receive 3 parameters:
- The starting position or character.
- The length.
If I have a string like the following:
$ string = "1,5,9,6,8," ;
The last comma may be over you.
How to remove the last character from a string with PHP?
To remove the last comma «,» how do I do it?
With the PHP substr function it is very simple but effective.
You can do it in the following way:
$ string = substr ( $ string , 0 , - 1 ) ; echo $ string ; // returns 1,5,9,6,8
By specifying a negative length, then that number of characters are omitted from the end of the string.
The starting position or character is set to 0 to take the entire string, and specifying a length of -1 removes the last character.
I hope it is useful for you. I have been using it very often. Therefore, it is a pleasure to share it.
Do you know of any other technique or way to remove the last character from a string? Submit a comment.
Didn’t what you want to do just come out? Ask for help and I will answer you as soon as possible.