13 Votes

PHP: Cut first and last Character from String

Question by Guest | Last update on 2024-01-16 | Created on 2015-06-25

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 (letters, numbers or punctuation marks) 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?

ReplyPositiveNegativeDateVotes
4Best Answer10 Votes

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

Here is a code example for its usage:

$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 use -1 as third parameter. A negative value ensures that the characters are counted from behind and with -1 we are cutting off exactly one character from the end of the string.
Last update on 2024-01-16 | Created on 2015-06-27

ReplyPositive Negative
33 Votes

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

Positive Negative
00 Votes

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

Positive Negative
Reply
00 Votes

How About This

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

ReplyPositive Negative
11 Vote

This returns an empty string and is not a solution for the question.
2019-04-28 at 21:23

Positive Negative
Reply
Reply

Related Topics

HTACCESS: Simplify URL

Tutorial | 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.