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?
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
PHP: Get first Digit of Number or String
Tutorial | 0 Comments
Rewrite Text Files with a fixed Line Length
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.
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:
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:
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