11 Vote

PHP: Remove last X Characters from End of String

Question by Guest | 2015-04-19 at 12:31

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?

7Best Answer7 Votes

You can use as a 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:

$s = "abcdefg";

echo substr($s, 0, -1);  // abcdef
echo substr($s, 0, -2);  // abcde
echo substr($s, 0, -4);  // abc

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.
2015-07-14 at 02:54

ReplyPositive Negative

Related Topics

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.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.