Home >Backend Development >PHP Tutorial >How to get last n characters of PHP string
Write a PHP program to get the last n characters of a given string.
Example:
输入: $str = "HTML!CSS!MySQL!PHP!" $n = 4 输出: PHP! 输入: $str = "HTML!CSS!MySQL!PHP!" $n = 10 输出: MySQL!PHP!
Method 1: In this method, iterate over the last N characters of the string and continue adding them appended to a new string.
Example:
<?php $str = "HTML!CSS!MySQL!PHP!"; $n = 4; $start = strlen($str) - $n; $str1 = ''; for ($x = $start; $x < strlen($str); $x++) { $str1 .= $str[$x]; } echo $str1; ?>
Output:
PHP!
Method 2: Another method is to use the built-in library function substr, where the parameter is a string name.
Example:
<?php $str = "HTML!CSS!MySQL!PHP!"; $n = 10; $start = strlen($str) - $n; $str1 = substr($str, $start); echo $str1; ?>
Output:
MySQL!PHP!
Note: In the above example, $start can also use -N to create the last n A substring of characters.
Related recommendations: "PHP Tutorial"http://www.php.cn/course/list/29.html
This article This article is about how to get the last n characters of a PHP string. I hope it will be helpful to friends in need!
The above is the detailed content of How to get last n characters of PHP string. For more information, please follow other related articles on the PHP Chinese website!