00 Votes

PHP: Cut out last Character from String

Question by Guest | 2015-04-18 at 17:14

It would like to read out the last character from a string using PHP. For example, when I have the string "abc", I would like to get the character "c".

Is there any simple PHP function to do something like that? Perhaps, I have to mention that the length of the string is arbitrary and the last character can be both, a letters as well as a number.

ReplyPositiveNegative
0Best Answer0 Votes

You can use the function substr().

Here is a small example for the application.

$s = "abc"

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

As you can see, we are starting with the string "abc" and we are getting the last character, that is "c". As a first parameter, we are passing the string we would like to process to substr(). After that, the starting position and then the number of characters that should be read out. Because we would like to count the start position from behind, we are using a negative value.

By the way, in this case, we can omit the third parameter and nevertheless we are getting the same result:

$s = "abc"

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

The reason is that if the third parameter is missing, substr() is returning the entire remaining string starting from the given start position. And if we are using -1 as starting position, in each case, the remaining string is exactly one character in length - which is the last character of our string we are searching for.
2015-04-18 at 22:26

ReplyPositive Negative
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.