0 2 Votes

PHP: Cut first and last Character from String

Question by Guest | 25/06/2015 at 20:24

I would like to remove the first and the last character from the beginning and from the end of an arbitrary string.

The characters can be of any kind (characters or numbers) and also the length of the string is arbitrary and can vary.

Is there any general PHP function that can shorten my string in this away?


Stefan Trost

Show Profile | Message
3Best Answer
9 Votes

You can use the PHP function substr() for cutting off your string at the front and at the back.

$s = "abcde";

echo substr($s, 1, -1);  // bcd

In this example, we are transforming the string "abcde" into "bcd". You can remove the first and the last character by passing 1 as second parameter and -1 as third parameter to substr().

The second parameter is determining at which position the resulting substring should start. Because the first character within a string has the position 0, we are passing 1 so that we can get all characters after the first character.

Because we do not know how long our sub string will become exactly, we are using -1 as third parameter. A negative value is ensuring that the characters are counted from behind and with -1 we are cutting off exactly one character from the end of the string.
27/06/2015 at 22:44

ReplyPositive Negative
11 Vote

Great! Thanks sir! The answer really simple and based on my problem. And Thanks! This solved my problem!
28/09/2018 at 03:35

Positive Negative
00 Votes

Thanks, mate! It works good. This solved my problem! )
26/03/2019 at 12:52

Positive Negative
00 Votes

How About This

echo substr($s, 0, 0); // ..??
27/04/2019 at 07:05

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 articles on askingbox.com. How to do.