Home >Backend Development >PHP Tutorial >How to get last n characters of PHP string

How to get last n characters of PHP string

藏色散人
藏色散人Original
2019-02-21 10:02:094861browse

Write a PHP program to get the last n characters of a given string.

How to get last n characters of PHP 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 = &#39;&#39;;   
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn