This article demonstrates how to extract the last n characters of a string in PHP.

The substr() function returns a substring as specified by the offset and length parameters. If the offset parameter is negative, the substring will begin at that position, counting from the string’s end. If the length parameter is omitted, the function returns a substring beginning at the offset and ending at the end of the string. You can use substr() to extract the last n characters of a string by taking an offset of -$n and skipping the length parameter. Note that the position is counted from the end of the string.

Download  Run Code

 
When working with multibyte character codes, it is safer to use the mb_substr() function. It requires the optional fourth parameter, which corresponds to the character encoding, to be used. The following code demonstrates the usage of mb_substr() by getting a substring of UTF-8 characters:

Download Code

That’s all about extracting the last n characters of a string in PHP.