PHP: Remove last X Characters from End of String
Question by Guest | Last update on 2021-07-06 | Created on 2015-04-19
I would like to edit an arbitrary string using PHP and to remove the last X characters from behind of the string.
The number of characters that should be deleted from the end of the string as well as the length of the input string may vary and therefore the procedure should be variable and should not depend on the content of the string.
For example, I would like to shorten the string "abcdefg" by the last two characters, so that I will get "abcde" as a result. Does someone know any PHP function for that?
Related Topics
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
MySQL: Line Breaks in MySQL
Tip | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
Textarea Maxlength: Limit Maximum Number of Characters in Textarea
Tutorial | 3 Comments
PHP Mail Function: UTF-8 E-Mail Headers
Info | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
You can use the function substr() provided by PHP for this. This function is giving you a sub string from an arbitrary string.
As a first parameter, we are passing the input string, as a second parameter the starting position and the length is the third parameter.
Let us have a look at an example:
Because we do not want to cut anything from the front, we are always using 0 as a starting point (the first character from the string has the position 0).
The most interesting thing is the last parameter. In order to cut a defined number of characters from the end independent from the string length, we have to use negative values here.
The negative values ensure that it is counted from behind and the specified number of characters will be removed. Accordingly, using -1 as parameter, makes the last character to be removed and -2 is deleting the last two characters and with passing -4, we are removing of the last four characters from our input string.
Last update on 2021-07-06 | Created on 2015-07-14