Home >Backend Development >PHP Problem >How to get the last few characters in php
In the process of PHP programming, sometimes we need to get only the last few characters of a string without getting its complete string. In this case, we can use some functions provided by PHP to accomplish this task easily.
This article will introduce some methods to get the last few characters of characters, as well as their advantages and disadvantages.
1. Use the substr function
The substr() function can be used to intercept a substring of a string and return this substring. The parameters passed to this function include the original string, the starting position of the substring, and the length of the substring.
To get the last few characters, we need to take the string length minus the number of characters that need to be obtained as the starting position, and set the substring length to the number of characters that need to be obtained. The following is an example:
$str = "Hello World!"; $last_chars = substr($str, -3); echo $last_chars; // 输出 "rld"
This code will output "rld", which is the last 3 characters of the original string.
2. Use the mb_substr function
If our string contains multi-byte characters, garbled characters may occur when using the substr() function. To solve this problem, we can use the mb_substr() function when dealing with multi-byte characters. It is similar to the substr() function, except that the mb_substr() function is more stable when handling multi-byte characters.
The following is an example of using the mb_substr() function to obtain the last 3 characters:
$str = "你好,世界!"; $last_chars = mb_substr($str, -3); echo $last_chars; // 输出 "界!"
3. Using the strrev and substr functions
Use the strrev() function to convert a character String reversed. We can first use this function to flip the original string, then use the substr() function to get the first few characters, and finally flip the obtained characters back.
The following is an example of getting the last 3 characters:
$str = "Hello World!"; $last_chars = strrev(substr(strrev($str), 0, 3)); echo $last_chars; // 输出 "rld"
Although this method is more troublesome, it may be faster in some scenarios that require extremely high performance.
Summary
The above are several ways to get the last few characters of a string. In the actual development process, we can choose different methods according to specific needs.
The recommended method is:
Thanks for reading this article, I hope it will be helpful to you.
The above is the detailed content of How to get the last few characters in php. For more information, please follow other related articles on the PHP Chinese website!