00 Votes

PHP: Read out n-th Character from behind of String

Question by Guest | 2015-07-13 at 19:58

I would like to read out a specific character from an arbitrary string. I know that it is possible to access individual characters from a string by using square brackets, for example with writing $s[2], I am able to get the third letter from the string $s.

However, I cannot use this, because I need the corresponding position counted from the end of the string. For example, I would like to retrieve the last character, the forelast character and the third-last character of a string having an arbitrary length.

Can someone give me an advice how to implement this using PHP? Is there even any predefined function for this?

ReplyPositiveNegative
0Best Answer0 Votes

In principle, you have several possibilities to cut out this character from your string.

Here is an example of how to read out the desired character using square brackets:

$s = $abcdef;

echo $s[strlen($s)-1]; // f
echo $s[strlen($s)-2]; // e
echo $s[strlen($s)-3]; // d

In order to get the characters from behind, first we are calculating the  entire length of the string using strlen($s) and we are subtracting the corresponding position from behind from the result. As an example, "strlen($s)-1" gives us the last position, "strlen($s)-2" is providing the last but not least position and so on.

Another way is to use the function substr() which is returning a sub-string from the string we have passed to the function. Here is another example for that:

$s = $abcdef;

echo substr($s, -1, 1); // f
echo substr($s, -2, 1); // e
echo substr($s, -3, 1); // d

The result is the same as from the first example. As the first parameter, we are passing the input string to substr(). Than the starting position of the desired part of the string from behind (we can do that by using negative values). As third parameter, we have to specify the length of the substring. In this case, that is always 1, because we are interested in exactly one character.
2015-07-13 at 23:36

ReplyPositive Negative
Reply

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.

Participate

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