Extract last ‘n’ characters of a string in PHP
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.
|
1 2 3 4 5 6 7 |
<?php $string = 'Hello, Techie'; $n = 6; $last_n = substr($string, -$n); echo $last_n; // prints Techie ?> |
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:
|
1 2 3 4 5 6 7 |
<?php $string = 'サンプルテキスト'; $n = 4; $last_n = mb_substr($string, -$n, null, 'UTF-8'); echo $last_n; // prints テキスト ?> |
That’s all about extracting the last n characters of a string in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)