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?
Related Topics
MySQL: Line Breaks in MySQL
Tip | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
PHP: Get first Digit of Number or String
Tutorial | 0 Comments
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
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.
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:
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
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
Thanks, mate! It works good. This solved my problem! :)
2019-03-26 at 12:52
How About This
echo substr($s, 0, 0); // ..??
2019-04-27 at 07:05
This returns an empty string and is not a solution for the question.
2019-04-28 at 21:23